[英]how to access a textbox in a grid in a stackpanel
I have the following code: 我有以下代码:
<StackPanel x:Name="ContentStackPanel">
<Grid>
<TextBlock Text="Min Value" />
<TextBox Text="{Binding MinValue}" />
</Grid>
<Grid>
<TextBlock Text="Max Value" />
<TextBox Text="{Binding MinValue}" />
</Grid>
</StackPanel>
I want to add a button so that I can clear the text in both TextBoxes. 我想添加一个按钮,以便可以清除两个TextBoxes中的文本。 This code doesn't work
此代码不起作用
private void ClearAllClick(object sender, RoutedEventArgs e)
{
foreach (TextBox tb in ContentStack.Children)
{
tb.Text = String.Empty;
}
}
how do I access the textbox inside the grid of ContentStackPanel? 如何访问ContentStackPanel网格内的文本框?
The Children
property only gives you immediate children, not all descendants. Children
属性仅给您直系孩子,而不是所有后代。 You could write a helper method to traverse the tree: 您可以编写一个辅助方法来遍历树:
private void ClearAllClick(object sender, RoutedEventArgs e)
{
ClearTextChildren(ContentStackPanel);
}
private void ClearTextChildren((Panel container)
{
foreach (var element in container.Children)
{
if (element is TextBox)
((TextBox)element).Text = String.Empty;
else if (element is Panel)
ClearChildren((Panel)element);
}
}
An alternative approach (probably better, since it's fragile to traverse UI trees in code) would be to use a Command
implementation on the button, instead of a click handler. 另一种方法(可能更好,因为遍历代码中的UI树很脆弱)是在按钮上使用
Command
实现,而不是单击处理程序。 This will allow you to clear the view-model properties instead of the text boxes themselves. 这将允许您清除视图模型属性,而不是文本框本身。
<Button x:Name="ClearAll" Command="{Binding ClearAllCommand}" />
"ClearAllCommand" should be in the same place as "MinValue" and "MaxValue": “ ClearAllCommand”应与“ MinValue”和“ MaxValue”放在同一位置:
public ICommand ClearAllCommand { get; private set; }
Using a standard DelegateCommand
implementation : 使用标准的
DelegateCommand
实现 :
ClearAllCommand = new DelegateCommand(arg => {
MinValue = null;
MaxValue = null;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.