xamarin.forms - 如何为控件模板提供 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>
我将BindingContext
我Homepage
的 in 代码设置在后面。
现在不应该ControlTemplate
继承主页的BindingContext
吗?因为我认为是这样,但我Label
并没有保留文本MyLabelText
。Bindings
在这些模板中可以使用哪些工作?
编辑:
使用此选项
<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>
解决方案
与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>
推荐阅读
- javascript - 我尝试使用 Js 和 CSS 创建选项卡,但它们不起作用
- python - 从 s3 Bucket 下载文件到 EC2 根路径
- node.js - Solidity:ParserError:预期的编译指示、导入指令或合同/接口/库定义
- android - RecyclerView 不显示项目
- mysql - 为什么 sqlite .dump 加密数据到 x'2384934..' 而不是原始数据?
- javascript - 画布到图像 base64 编码的 url 不显示图像
- android - 测试 ION 驱动程序时,libion 中的 DMAReadCached 失败
- android - 为什么 Chronometer 类中的 isTheFinalCountDown 方法会打开 YouTube 视频?
- javascript - table row not append to division table through javascript
- asp.net-mvc - Sending large data to wcf service returns me "504 (Gateway Time-out) error"