xamarin.forms - 如何为控件模板提供 BindingContext

标签 xamarin.forms binding controltemplate

我在 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 不应该继承 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/

相关文章:

c# - System.DllNotFoundException :/system/lib/libsqlite. 所以

master-detail - Xamarin Forms 主详细信息页面图标和菜单图标

c# - 尝试访问 Xamarin.Forms Android 上的服务器时引发 System.AggregateException

android - 为什么 Service 在 Activity 被销毁时会 self 销毁?

wpf - 在 MouseOver 上更改用作按钮模板的路径的填充颜色

wpf - 防止 ControlTemplate 中的控件继承全局样式 (WPF)

wpf - 如何更改 WPF CheckBox 控件中 CheckMark 的颜色?

c# - Windows 10 移动版不遵守 KeyboardFlags.None

c# - 使用 xaml 绑定(bind)和 View 模型执行带有参数的命令

WPF 与 PlacementTarget 和 RelativeSource 绑定(bind)