C# 从codebehind访问按钮样式中的文本块文本

C# 从codebehind访问按钮样式中的文本块文本,c#,wpf,xaml,controltemplate,C#,Wpf,Xaml,Controltemplate,如何从自定义样式的代码隐藏访问tbRegistrationBtn.text属性 正在从codebehind动态创建“我的按钮”,并将其添加到父控件(stackpanel): 当我按下屏幕上的另一个按钮时,就会创建该按钮 代码隐藏: Button newBtn = new Button(); newBtn.Width = 160; newBtn.Height = 46;

如何从自定义样式的代码隐藏访问tbRegistrationBtn.text属性

正在从codebehind动态创建“我的按钮”,并将其添加到父控件(stackpanel): 当我按下屏幕上的另一个按钮时,就会创建该按钮

代码隐藏:

                Button newBtn = new Button();
                newBtn.Width = 160;
                newBtn.Height = 46;
                newBtn.Style = this.FindResource("ButtonStyleRegistration") as Style;
                spHorizontal.Children.Add(newBtn);
Xaml:


致以最诚挚的问候。

您可以使用VisualTreeHelper在按钮的可视树中导航。使用此辅助功能:

public static T FindVisualChild<T>(DependencyObject obj, string name)
    where T : DependencyObject
{
    var count = VisualTreeHelper.GetChildrenCount(obj);
    for(int i = 0; i < count; i++)
    {
        var child = VisualTreeHelper.GetChild(obj, i);

        if(child != null)
        {
            var res = child as T;
            if(res != null && (string)res.GetValue(FrameworkElement.NameProperty) == name)
            {
                return res;
            }
            res = FindVisualChild<T>(child, name);
            if(res != null) return res;
        }
    }

    return null;
}
最后设置
TextBlock
text:

var tb = FindVisualChild<TextBlock>(newBtn, "tbRegistrationBtn");
tb.Text = "Registration";
var tb=FindVisualChild(newBtn,“tbRegistrationBtn”);
tb.Text=“注册”;

谢谢,一串非常好用!没想到访问一个简单的控件会这么复杂。@Rakr:已经有一种方法可以在模板中查找控件,它叫做,人们真的喜欢无缘无故地抛出
FindVisualChild
方法。@Rakr:如果有些事情很难做到,那么很可能你一开始就不打算这么做(在这一点上,我会指出Silvermind的答案)。
public static T FindVisualChild<T>(DependencyObject obj, string name)
    where T : DependencyObject
{
    var count = VisualTreeHelper.GetChildrenCount(obj);
    for(int i = 0; i < count; i++)
    {
        var child = VisualTreeHelper.GetChild(obj, i);

        if(child != null)
        {
            var res = child as T;
            if(res != null && (string)res.GetValue(FrameworkElement.NameProperty) == name)
            {
                return res;
            }
            res = FindVisualChild<T>(child, name);
            if(res != null) return res;
        }
    }

    return null;
}
newBtn.ApplyTemplate();
var tb = FindVisualChild<TextBlock>(newBtn, "tbRegistrationBtn");
tb.Text = "Registration";