从后面的代码访问Button Style中的Textblock文本

时间:2012-03-15 08:07:27

标签: c# wpf xaml controltemplate

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

我的按钮是从代码隐藏动态创建的,并被添加到父控件(stackpanel): 当我按下屏幕上的其他按钮时,按钮会被创建。

代码隐藏:

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

的Xaml:

        <Style x:Key="ButtonStyleRegistration" TargetType="{x:Type Button}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Grid x:Name="registrationButton">
                        <Rectangle Fill="#FF89959A" Height="Auto" RadiusY="15" RadiusX="15" Stroke="White" Width="Auto"/>
                        <TextBlock x:Name="tbRegistrationBtn" TextWrapping="Wrap" Text="" HorizontalAlignment="Center" Margin="7.5,14.973,0,16.84" d:LayoutOverrides="Height"/>
                    </Grid>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsFocused" Value="True"/>
                        <Trigger Property="IsDefaulted" Value="True"/>
                        <Trigger Property="IsMouseOver" Value="True"/>
                        <Trigger Property="IsPressed" Value="True"/>
                        <Trigger Property="IsEnabled" Value="False"/>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
        <Setter Property="FontSize" Value="10.667"/>
    </Style> 

任何检索文本块的尝试都会导致null错误。 尝试:

            Style style = this.FindResource("ButtonStyleRegistration") as Style;
            newBtn.Style = style;
            TextBlock tb = (TextBlock)style.Resources.FindName("tbRegistrationBtn");
            tb.Text = "test";

最好的问候。

2 个答案:

答案 0 :(得分:0)

您可以使用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;
}

此外,你需要强制你的按钮基于模板构建它的可视化树(因为它默认是延迟的):

newBtn.ApplyTemplate();

最后设置TextBlock文字:

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

答案 1 :(得分:0)

max的答案绝对适合您的情况。 但是,为什么不这样做:

<TextBlock TextWrapping="Wrap" Text="{TemplateBinding Content}"
           HorizontalAlignment="Center" Margin="7.5,14.973,0,16.84"/>

可以在代码隐藏中设置newBtn.Content = "test"