如何在 UWP 的 ControlTemplate 中使用 x:bind

How to use x:bind inside ControlTemplate in UWP

您好,我只是想在 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 吗?

基于此document,当您尝试在 ControlTemplate 中使用 x:bind 时,您需要添加 TargetType 属性(例如<ControlTemplate TargetType="Button">)。但是x:bind的功能和TemplateBinding一样,只能绑定Button的属性,所以如果要绑定在code-behind中声明的属性,会更好使用 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;

Another scenario can we bind txtWidth using Binding or x:Bind in Ellipse Width here?

如果要将 txtWidth 的宽度与 Ellipse 的宽度绑定,可以使用 ElementName 找到 txtWidth 元素并使用绑定与其宽度绑定。

<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>