xaml - 如何在 UWP 中的 ControlTemplate 中使用 x:bind
问题描述
嗨,我只是想在 UWP 中的 Button 的 ControlTemplate 中使用 x:Bind,我的简单代码如下,
<Grid>
<TextBox x:Name="txtWidth"/>
<Button x:Name="btnEllipse" PointerEntered="btnEllipse_PointerEntered" PointerExited="btnEllipse_PointerExited" Click="btnEllipse_Click">
<Button.Template>
<ControlTemplate>
<Ellipse x:Name="myEll" Width="{x:Bind ShapeWidth,Mode=OneWay}" Height="{Binding Width,ElementName=myEll}" Fill="Purple" Stroke="Black" StrokeThickness="2" />
</ControlTemplate>
</Button.Template>
</Button>
</Grid>
C# 代码隐藏文件
double _shapeWidth= 100;
public Double ShapeWidth
{
get { return _shapeWidth; }
set { _shapeWidth = value; }
}
我收到错误, 目标类型需要在 ControlTemplate 中使用 x:Bind 请让我知道我在哪里犯了错误,?
另一种情况我们可以在这里使用 Binding 或 x:Bind in Ellipse Width 来绑定 txtWidth 吗?
解决方案
根据此文档,当您尝试在 ControlTemplate 中使用 x:bind 时,您需要添加TargetType属性(例如<ControlTemplate TargetType="Button">
)。但是 x:bind 的功能和 TemplateBinding 一样,只能与 Button 的属性进行绑定,所以如果要与在代码隐藏中声明的属性进行绑定,最好使用Binding并声明DataContext。例如:
.xaml:
<Button x:Name="btnEllipse" PointerExited="btnEllipse_PointerExited" Click="btnEllipse_Click">
<Button.Template>
<ControlTemplate>
<Ellipse x:Name="myEll" Width="{Binding ShapeWidth}" Height="{Binding Width,ElementName=myEll}" Fill="Purple" Stroke="Black" StrokeThickness="2" />
</ControlTemplate>
</Button.Template>
</Button>
。CS:
this.DataContext = this;
另一种情况我们可以在这里使用 Binding 或 x:Bind in Ellipse Width 来绑定 txtWidth 吗?
如果要将 txtWidth 的宽度与 Ellipse 的宽度绑定,可以使用 ElementName 找到 txtWidth 元素并使用 binding 与它的宽度进行绑定。
<TextBox x:Name="txtWidth" Width="100" Text="efwiehfiweh"/>
<Button x:Name="btnEllipse" PointerExited="btnEllipse_PointerExited" Click="btnEllipse_Click">
<Button.Template>
<ControlTemplate>
<Ellipse x:Name="myEll" Width="{Binding Width,ElementName=txtWidth,Mode=OneWay}" Height="{Binding Width,ElementName=myEll}" Fill="Purple" Stroke="Black" StrokeThickness="2" />
</ControlTemplate>
</Button.Template>
</Button>
推荐阅读
- excel - excel用不同的分隔符分割字符串
- python - Python POST 仅在我在 POST 之前获得 CSRF 令牌时才有效,为什么?
- xml - Vim 奇怪地自动缩进 xml
- typescript - 第三方函数的“对象”类型上不存在属性
- javascript - Javascript Axios 获取条件参数
- roslyn - 使用 Roslyn 从基本构造函数调用站点获取参数名称
- php - PHP如何为以下json结构正确合并数组
- cornerstonejs - 基石工具未加载内置工具
- python - 如何在 Python 中实现支持 __getitem__ 的对象的 del ?
- html - 如何在 kableExtra HTML 表格中使用 unicode 符号