如何在代码隐藏中访问Button.Content中的控件?

问题描述:

在XAML我已经创建了一个按钮是这样的:如何在代码隐藏中访问Button.Content中的控件?

<Button MouseEnter="Button_MouseEnter"> 
    <Button.Content> 
     <Grid> 
      <Grid.RowDefinitions> 
       <RowDefinition/> 
       <RowDefinition/> 
       <RowDefinition/> 
      </Grid.RowDefinitions> 

      <TextBlock Grid.Row="0" Text="asd"/> 
      <Label Grid.Row="1" Content="xxx"/> 
      <Label Grid.Row="2" Content="yyy"/> 
     </Grid> 
    </Button.Content> 
</Button> 

现在我需要访问这些控件的一个按钮内容的内部代码隐藏。假设我需要TextBlock之一。

private void Button_MouseEnter(object sender, MouseEventArgs e) 
    { 
     Button button = (Button)sender; 
     // ? 
    } 

我该怎么做? 另外我有多个按钮,就像这个自动创建的数据绑定。 我需要访问这些控件的原因是我想在某些情况下为其中的一个设置动画。

+0

是否试图直接在XAML中使用触发器,以便为按钮设置动画效果? – 2012-07-25 08:15:06

+0

你的button.Content应该是一个Grid,对吧?你可以施放它。 – 2012-07-25 08:15:33

+0

我的动画需要大量的计算,我不想为此创建太多的转换器。 @LuisFilipe:这个技巧:)简单。谢谢! – jacek11 2012-07-25 08:19:03

你的button.Content应该是Grid,对吧?你可以转换成吧。

 private void Button_MouseEnter(object sender, MouseEventArgs e) 
    { 
     Button b = sender as Button; 
     TextBox textBox = null; 
     if (b != null) 
     { 
      foreach (var frameworkElement in ((Grid)b.Content).Children) 
      { 
       if (frameworkElement is TextBox) 
       { 
        textBox = (TextBox)frameworkElement; 
        break; 
       } 
      } 

     } 
    } 

这只是为了说明如何提取网格的孩子,这是你的按钮的内容。我希望这会帮助你明白。

如果你想改变这样的事情,我会建议使用MVVM模式和DataBinding!

=>为文本创建属性并将文本框绑定到该文本,而不必更改此属性,并且该按钮将更改其文本。查看MVC的PropertyChanged-Event!