【问题标题】:How to provide BindingContext to Control template如何为控件模板提供 BindingContext
【发布时间】:2019-09-02 17:04:26
【问题描述】:

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

我在后面的代码中设置了HomepageBindingContext

现在ControlTemplate 不应该继承主页的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>

【问题讨论】:

  • 看看document 和那里的样本。
  • @JackHua-MSFT 你能看看我编辑的问题吗?谢谢链接

标签: xamarin.forms binding controltemplate


【解决方案1】:

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>

【讨论】:

  • 这不起作用,因为我的ControlTemplate 在 ContentPage 属性中,而不是在正文中。仅当我将 ControlTemplate 放在正文中时,此选项才有效
  • @Greggz 您将此标记为正确?请解释一下,我和你有同样的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多