private bool CheckGrid(Grid grid) { foreach (var child in grid.Children.OfType()) { 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; }

//使用反射和委托优化 private bool CheckGrid(Grid grid) { var checkEmpty = new Func<FrameworkElement, bool>(child => { 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; });

return grid.Children.OfType<FrameworkElement>().All(checkEmpty);

}

C# 代码优化:使用反射和委托验证 Grid 内容

原文地址: https://www.cveoy.top/t/topic/j499 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录