我在 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
的 header 中使用了 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>
最佳答案
ControlTemplate
控件的绑定(bind)略有不同。查看这些文档:https://learn.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>
关于xamarin.forms - 如何为控件模板提供 BindingContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55643031/