2012-03-15 132 views
0

一个的ButtonStyle内艾策斯文本块文本如何从后面代码定制的风格访问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> 

任何试图检索一个空的错误文字块的结果。 尝试:

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

此致敬礼。

回答

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"; 
+0

谢谢你一堆完美的作品!没想到访问一个简单的控件会很复杂。 – Rakr 2012-03-15 08:44:13

+0

@Rakr:已经有一种方法来查找模板中的控件,它被称为['FindName'](http://msdn.microsoft.com/en-us/library/system.windows.frameworktemplate.findname.aspx) ,人们真的很喜欢抛弃'FindVisualChild'方法,原因不明。 – 2012-03-17 04:01:27

+0

@Rakr:另外如果有什么事情很难做到的话,那么你首先不会*意味着*做到这一点(在那个笔记上我会指向Silvermind的答案)。 – 2012-03-17 04:07:18

0

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

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

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