首页 > 解决方案 > 如何为控件模板提供 BindingContext

问题描述

我在 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>

我将BindingContextHomepage的 in 代码设置在后面。

现在不应该ControlTemplate继承主页的BindingContext吗?因为我认为是这样,但我Label并没有保留文本MyLabelTextBindings在这些模板中可以使用哪些工作?

编辑:

使用此选项

<ResourceDictionary>
        <ControlTemplate x:Key="HomePageTemplate">
            <Label Text="{TemplateBinding Parent.BindingContext.MyLabelText}"/>
        </ControlTemplate>
</ResourceDictionary>

也对我不起作用,因为我ControlTemplate在标题中使用,HomePage而不是在正文中。

这有效,但这不是我要找的:

<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>

标签: xamarin.formsbindingcontroltemplate

解决方案


ControlTemplate控件的绑定略有不同。看看这些文档:https ://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/templates/control-templates/template-binding

假设该MyLabelText属性是BindingContext父控件的一部分,您的代码可能如下所示:

<ResourceDictionary>
        <ControlTemplate x:Key="HomePageTemplate">
            <Label Text="{TemplateBinding Parent.BindingContext.MyLabelText }"/>
        </ControlTemplate>
</ResourceDictionary>

推荐阅读