UWP [Xaml]如何访问Button内的元素

时间:2017-04-01 15:18:42

标签: c# xaml

初始化UserControl后,如何在C#代码中更改 txtPIN.Text 值。

这是XAML

<Button x:Name="btn_pin" Content="Change PIN" Click="button_Click" Foreground="White">
            <Button.Template>
                <ControlTemplate TargetType="Button">
                    <StackPanel  Orientation="Horizontal" VerticalAlignment="Center">
                        <Image Source="/Assets/images/settings/lock.png" Stretch="UniformToFill" Width="16" Height="16"/>
                        <TextBlock x:Name="txtPin" Text="Change PIN" Foreground="White" />
                    </StackPanel>
                </ControlTemplate>
            </Button.Template>
        </Button>

和C#

public MyUserControl()
    {
        this.InitializeComponent();
        this.btn_pin.??????????
    }

1 个答案:

答案 0 :(得分:0)

您没有以正确的方式执行此操作,只需修复您的xaml(我更改了TextBlock的Text绑定):

<Button x:Name="btn_pin" Content="Change PIN" Click="button_Click" Foreground="White">
            <Button.Template>
                <ControlTemplate TargetType="Button">
                    <StackPanel  Orientation="Horizontal" VerticalAlignment="Center">
                        <Image Source="/Assets/images/settings/lock.png" Stretch="UniformToFill" Width="16" Height="16"/>
                        <TextBlock x:Name="txtPin" Text="{TemplateBinding Content}" Foreground="White" />
                    </StackPanel>
                </ControlTemplate>
            </Button.Template>
        </Button>

每次要更改文本时,请更改按钮的内容,如下所示:

    public MainPage()
    {
        this.InitializeComponent();
        btn_pin.Content = "New label";
    }