0
Follow
0
View

Changing Text value of TextBlock embedded within a Control Template

sonbinsonbin 注册会员
2023-01-25 23:55

You should reference the template of the button like this..

private void panelBtn_Click(object sender, RoutedEventArgs e)
{
    if (sender is Button btn)
    {
        var text = btn.Template.FindName("txtBlk", btn) as TextBlock;
        text.Text = txtBox.Text;
    }
}
hainancyp 注册会员
2023-01-25 23:55

@MuhammadSulaiman answered you correctly, but I would suggest that you change the implementation.
Rather than looking for an element in a template, it's better to add a resource to which this element will refer and change this resource.


Text">Some Text








private void panelBtn_Click(object sender, RoutedEventArgs e)
{
    if (sender is FrameworkElement elm)
    {
        elm.Resources["button.Text"] = txtBox.Text;
    }
}

You can also change the initial text in XAML:

    

In the same way, you can set a common initial text for all buttons located in one common container, through the resources of this container.