[英]How to access controls in Button.Content in code-behind?
在XAML中,我創建了一個如下所示的Button:
<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>
現在,我需要在代碼隱藏中訪問Button內容內部的那些控件之一。 可以說我需要一個TextBlock。
private void Button_MouseEnter(object sender, MouseEventArgs e)
{
Button button = (Button)sender;
// ?
}
我怎樣才能做到這一點? 我也有多個像這樣的按鈕,它們是通過數據綁定自動創建的。 我需要訪問這些控件的原因是,我想在某些情況下為其中的一個設置動畫。
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;
}
}
}
}
這只是為了讓您知道如何提取作為按鈕內容的Grid子級。 我希望這會幫助您理解。
您的button.Content應該是Grid ,對吧? 你可以投下它。
如果您想更改此類內容,我建議使用MVVM模式和DataBinding!
=>為該文本創建一個屬性並將文本框綁定到該文本,這比您只需要更改此屬性和按鈕將更改其文本即可。 請參閱MVVM的PropertyChanged-Event!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.