我在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的Homepage设置为后面的代码。
现在ControlTemplate不应该继承主页的BindingContext吗?因为我认为是这样的,但是我的Label并没有阻止MyLabelText的文本。在这些模板中使用Bindings需要做些什么?
编辑:
使用此选项
<ResourceDictionary>
<ControlTemplate x:Key="HomePageTemplate">
<Label Text="{TemplateBinding Parent.BindingContext.MyLabelText}"/>
</ControlTemplate>
</ResourceDictionary>也不适用于我,因为我在HomePage的头中使用了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>发布于 2019-04-12 02:33:50
对于ControlTemplate控件,绑定略有不同。看看这些文档: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>发布于 2022-07-04 10:13:35
App.xaml应该有一个BindingContext。让我们称它为AppViewmodel,在App.xaml顶部定义一个名称空间vm (或任何其他键)。这个AppViewmodel可以从ControlTemplate中绑定到。在本例中,一个按钮(放置在堆栈布局中)绑定到一个名为AppCommand的命令,该命令驻留在AppViewmodel中。当此ControlTemplate应用于ContentPage中时,它绑定到ViewModel of App.xaml,而不是绑定到特定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>发布于 2022-07-05 03:32:38
如果有人感兴趣,它的工作方式就是在TemplateBinding之后添加路径,在它上指定BindingContext,然后是公共变量名:
<ResourceDictionary>
<ControlTemplate x:Key="HomePageTemplate">
<Label Text="{ TemplateBinding Path=BindingContext.MyLabelText }"/>
</ControlTemplate>
</ResourceDictionary>https://stackoverflow.com/questions/55643031
复制相似问题