我有3个stack panels
持有标签,textbox
包含在一个大堆栈面板中,所以它看起来像这样:
<StackPanel Name="stackControls" Grid.Row="1" Orientation="Vertical" VerticalAlignment="Center" HorizontalAlignment="Center">
<StackPanel HorizontalAlignment="Right" Orientation="Horizontal" Grid.Row="1" VerticalAlignment="Center">
<Label x:Name="lblName" Content="Broj kase:" Foreground="Black" FontSize="14" VerticalAlignment="Center"/>
<TextBox Name="txtName" VerticalContentAlignment="Center" FontSize="15" Foreground="Black" FontFamily="Arial" Style="{StaticResource TextBoxStyle1}" Width="500" Height="45" />
</StackPanel>
<StackPanel HorizontalAlignment="Right" Margin="0,5,0,0" Orientation="Horizontal" Grid.Row="1" VerticalAlignment="Center">
<Label x:Name="lblLastName" Content="Generični printer:" Foreground="Black" FontSize="14" VerticalAlignment="Center"/>
<TextBox Name="txtLastName" VerticalContentAlignment="Center" FontSize="15" FontFamily="Arial" Width="500" Style="{StaticResource TextBoxStyle1}" Height="45" />
</StackPanel>
<StackPanel HorizontalAlignment="Right" Margin="0,5,0,0" Orientation="Horizontal" Grid.Row="1" VerticalAlignment="Center">
<Label x:Name="lblHeader" Content="Veličina naslova na gridu:" Foreground="Black" FontSize="14" VerticalAlignment="Center"/>
<TextBox Name="txtHeader" VerticalContentAlignment="Center" FontSize="15" FontFamily="Arial" Width="500" Style="{StaticResource TextBoxStyle1}" Height="45" />
</StackPanel>
</StackPanel>
我必须拒绝用户编辑任何字段txtName,txtLastName或txtHeader以留空字段,所以我想循环遍历每个stackpanel并通过每个文本框检查文本是否为空,如果是,我会返回并抛出他是一个弹出窗口,上面写着:有些字段是空的,如果我可以准确指定哪些字段,那可能会很棒,也许我可以使用标签......?
这是我到目前为止所尝试的:
foreach (var c in this.stackControls.Children)
{
if (c is StackPanel)
{
TextBox textBox = c as TextBox;
if (String.IsNullOrEmpty(textBox.Text))
{
MessageBox.Show("Some fields are empty.",
"Edit",
MessageBoxButton.OK,
MessageBoxImage.Information);
return;
}
}
}
但是使用上面的代码我总是只通过容器(那3个堆栈面板)循环,我不能每个文本框...
谢谢你们 干杯
答案 0 :(得分:1)
您可以使用以下帮助程序方法查找可视树中TextBox
的所有StackPanel
子项:
Find all controls in WPF Window by type
foreach (var textBox in FindVisualChildren<TextBox>(stackControls))
{
if (String.IsNullOrEmpty(textBox.Text))
{
MessageBox.Show(textBox.Name + " is empty.",
"Edit",
MessageBoxButton.OK,
MessageBoxImage.Information);
return;
}
}
答案 1 :(得分:0)
stackControls
堆栈面板的Children属性仅返回其中
直系儿童,即三个堆叠面板。所以你应该使用嵌套循环来获取文本框:
foreach (var childPanel in this.stackControls.Children)
{
if (childPanel is StackPanel)
{
foreach (var c in ((StackPanel)childPanel).Children)
{
TextBox textBox = c as TextBox;
if (String.IsNullOrEmpty(textBox.Text))
{
MessageBox.Show("Some fields are empty.",
"Edit",
MessageBoxButton.OK,
MessageBoxImage.Information);
return;
}
}
}
}