WPF 判断Grid控件的子控件不能为空子控件有TextBoxTextBlockComboBox按逻辑给出一个优化后的代码
以下是一个优化后的代码示例,使用了LINQ和递归函数来遍历Grid控件的子控件并判断是否为空:
private bool CheckGrid(Grid grid)
{
foreach (var child in grid.Children.OfType<FrameworkElement>())
{
if (child is TextBox textBox && string.IsNullOrEmpty(textBox.Text))
{
return false;
}
else if (child is TextBlock textBlock && string.IsNullOrEmpty(textBlock.Text))
{
return false;
}
else if (child is ComboBox comboBox && comboBox.SelectedItem == null)
{
return false;
}
else if (child is Grid childGrid && !CheckGrid(childGrid))
{
return false;
}
}
return true;
}
这个函数接受一个Grid控件作为参数,并使用LINQ的OfType方法来筛选出其中的FrameworkElement子控件。然后,对于每个子控件,使用if语句来判断其类型并检查其内容是否为空。如果子控件是一个Grid控件,则递归调用CheckGrid函数来检查其子控件。最后,如果所有子控件均不为空,则返回true,否则返回false
原文地址: http://www.cveoy.top/t/topic/cEqc 著作权归作者所有。请勿转载和采集!