首页 > 解决方案 > 如何在 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 吗?

标签: xamluwpuwp-xaml

解决方案


根据此文档,当您尝试在 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>

推荐阅读