using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Media.Effects;
namespace WpfApplication1
{
//拖了3个TextBox控件,2个ComboBox控件到窗体
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
// comboBox1.Effect = new DropShadowEffect { Color = Colors.Red };
}
/// <summary>
/// 检查TextBox控件的值是否为空。
/// </summary>
/// <param name="isOK">如果发现TextBox.Text的值为空,则将isOK设为false</param>
/// <param name="textBox">要检查的TextBox集合</param>
private void CheckTextBoxNotEmpty(ref bool isOK, params TextBox[] textBoxs)
{
foreach (TextBox txtBox in textBoxs)
{
if (txtBox.Text.Length <= 0)
{
isOK = false;
//将当前的TextBox的背景设为红色
txtBox.Background = Brushes.Red;
}
else
{
//否则将TextBox的背景色设为默认值
txtBox.Background = null;
}
}
}
/// <summary>
/// 检查ComboBox控件的下拉菜单是否有选中值
/// </summary>
/// <param name="isOK">如果没选中就将isOK设为false</param>
/// <param name="comboBoxs">要检查的控件</param>
private void CheckComboBoxNotEmpty(ref bool isOK, params ComboBox[] comboBoxs)
{
foreach (ComboBox combo in comboBoxs)
{
if (combo.SelectedIndex < 0)
{
isOK = false;
//将ComboBox控件的背景色设为红色
combo.Effect = new DropShadowEffect() { Color = Colors.Red };
}
else
{
//将ComboBox控件的背景色设为默认
combo.Effect = null;
}
}
}
private void btnCheck_Click(object sender, RoutedEventArgs e)
{
//数据检查是否为空,默认通过的(也就是说默认是不为空,当用ref的形式将要检查的数据传给CheckTextBoxEmpty方法检查,如果检查到其中的某个控件的值为空的话,就将isOK设为false,然后给那个控件的背景色设为红色)
bool isOK = true;
//检查TextBox控件的值是否为空。
CheckTextBoxNotEmpty(ref isOK,textBox1,textBox2,textBox3);
//检查ComboBox控件的下拉菜单是否有选中值
CheckComboBoxNotEmpty(ref isOK, comboBox1, comboBox2);
//如果没有通过数据检查合法性(如果通过检查isOK为false的时候)则不保存
if(!isOK)
{
return;
}
}
}
}
非映射的形式检查TextBox,ComboBox控件的值是否为空(是否被选中)
最新推荐文章于 2022-02-08 15:42:31 发布