Xamarin 模板控件相对源绑定



目前 Xamarin 命令行管理程序导航存在问题,导致目标页面的内容隐藏在页面顶部的导航栏下方。 我正在尝试制作一个控件模板,以将内容包装在一个具有足够上边距的容器中,以便将内容从导航栏下方推到屏幕上。 按照这里的指导,我目前拥有的——

<?xml version="1.0" encoding="utf-8" ?>
<Application xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="Y12.Mobile.MovePlan.App">
<Application.Resources>
<ResourceDictionary>
<ControlTemplate x:Key="NavBarContentControlTemplate">
<StackLayout
BindingContext="{Binding Source={RelativeSource TemplatedParent}}"
Margin="0, 50, 0, 0">
<Label Text="Hello Template!"></Label>
<ContentView Content="{Binding Content}"></ContentView>
</StackLayout>
</ControlTemplate>
</ResourceDictionary>
</Application.Resources>
</Application>

——似乎行不通。 我在{RelativeSource TemplatedParent}得到一个智能感知突出显示,XLS0414出现以下错误:

找不到类型"相对源"。验证是否没有缺少程序集引用,并且已生成所有引用的程序集。

我需要做什么才能在此处正确设置BindingContext

看起来我需要进一步阅读页面。 稍后它有一个部分描述如何使用模板绑定传递参数,其中指出,

TemplateBinding 标记扩展是创建控件模板的替代方法,该控件使用 RelativeSource 标记扩展将模板中根元素的 BindingContext 设置为其模板化的父级。模板绑定标记扩展消除了 RelativeSource 绑定,并将绑定表达式替换为模板绑定表达式。

更进一步,

使用

TemplateBinding 标记扩展等效于使用 RelativeSource 标记扩展将模板中根元素的 BindingContext 设置为其模板化父元素,然后使用 Binding 标记扩展解析子对象的绑定。实际上,TemplateBinding 标记扩展创建了一个绑定,其源是 RelativeBindingSource.TemplatedParent。

应用它,我能够将上面的代码更改为以下内容:

<?xml version="1.0" encoding="utf-8" ?>
<Application xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="Y12.Mobile.MovePlan.App">
<Application.Resources>
<ResourceDictionary>
<ControlTemplate x:Key="NavBarContentControlTemplate">
<StackLayout
Margin="0, 50, 0, 0">
<Label Text="Hello Template!"></Label>
<ContentView Content="{TemplateBinding Content}"></ContentView>
</StackLayout>
</ControlTemplate>
</ResourceDictionary>
</Application.Resources>
</Application>

而且效果很好。

最新更新