如何为控件模板提供 BindingContext

3
我在App.Xaml中定义了一个模板。
<ResourceDictionary>
        <ControlTemplate x:Key="HomePageTemplate">
            <Label Text="{Binding MyLabelText}"/>
        </ControlTemplate>
</ResourceDictionary>

我在我的首页中使用它。
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
            xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
            xmlns:cv="clr-namespace:Xamarin.Forms;assembly=Xamarin.Forms.CarouselView"
            xmlns:local="clr-namespace:App.Converters"
            x:Class="App.Views.HomePage"
            ControlTemplate="{StaticResource HomePageTemplate}">

</ContentPage>

我在代码中设置了Homepage的BindingContext。那么控件模板(ControlTemplate)不应该继承HomePage的BindingContext吗?因为我认为是这样的,但我的标签(Label)没有保留MyLabelText的文本。在这些模板中使用绑定(Bindings)有什么解决方法吗?
编辑:使用以下选项:
<ResourceDictionary>
        <ControlTemplate x:Key="HomePageTemplate">
            <Label Text="{TemplateBinding Parent.BindingContext.MyLabelText}"/>
        </ControlTemplate>
</ResourceDictionary>

这对我也不起作用,因为我在HomePage的标题中使用了ControlTemplate而不是在其主体中。

这种方法可行,但不是我要找的:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
            xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
            xmlns:cv="clr-namespace:Xamarin.Forms;assembly=Xamarin.Forms.CarouselView"
            xmlns:local="clr-namespace:App.Converters"
            x:Class="App.Views.HomePage"
            >
  <ContentView ControlTemplate="{StaticResource HomePageTemplate}" />
</ContentPage>

请查看文档以及其中的示例。 - nevermore
@JackHua-MSFT,你能看一下我编辑过的问题吗?感谢提供链接。 - Greggz
3个回答

4

这不起作用是因为我的ControlTemplate在ContentPage属性中,而不是在主体中。只有当我将ControlTemplate放在主体中时,此选项才会起作用。 - Greggz
1
@Greggz 你标记这个为正确的?请解释一下,我也遇到了同样的问题。 - Ruddy

0

App.xaml应该有一个BindingContext。我们称之为AppViewmodel,在App.xaml顶部定义了一个命名空间vm(或任何其他键)。这个AppViewmodel可以从ControlTemplate内部绑定。在这个例子中,一个按钮(放置在stacklayout中)绑定到一个名为AppCommand的命令,该命令位于AppViewmodel中。当这个ControlTemplate应用于ContentPage时,它绑定到App.xaml的ViewModel,而不是那个特定ContentPage的VM。也许后者也是可能的,例如通过选择正确的RelativeSource和AncestorType设置,但我还没有弄清楚。 参见

     <ControlTemplate x:Key="HomePageTemplate">
            <StackLayout BindingContext="{Binding Source={RelativeSource TemplatedParent}}">
                    <Button 
Command="{Binding Source={RelativeSource AncestorType={x:Type vm:AppViewModel}}, Path=AppCommand}"
                            />
            </StackLayout>
    </ControlTemplate>

0
如果有人感兴趣,这个工作原理只是在TemplateBinding后添加Path,在其上指定BindingContext,然后公共变量名称:
<ResourceDictionary>
    <ControlTemplate x:Key="HomePageTemplate">
        <Label Text="{ TemplateBinding Path=BindingContext.MyLabelText }"/>
    </ControlTemplate>
</ResourceDictionary>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接