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. 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?
The Children
property only gives you immediate children, not all descendants. 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. 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":
public ICommand ClearAllCommand { get; private set; }
Using a standard DelegateCommand
implementation :
ClearAllCommand = new DelegateCommand(arg => {
MinValue = null;
MaxValue = null;
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.