wpf 如何在 DataGrid 中验证 Null 或 Empty 单元格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24686101/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to validate Null or Empty cell in DataGrid
提问by Vishal
I am trying to Validate a cell in DataGrid. This is my first approach to validation. I get some problems with validations as I am new to it.
我正在尝试验证 DataGrid 中的单元格。这是我的第一种验证方法。因为我是新手,所以我在验证方面遇到了一些问题。
I have created a class called StringIsNullOrEmptyValidationRule.cs. This class checks if string is null or ""
我创建了一个名为 StringIsNullOrEmptyValidationRule.cs 的类。此类检查字符串是否为空或“”
Here is the code of StringIsNullOrEmptyValidationRule.cs :
这是 StringIsNullOrEmptyValidationRule.cs 的代码:
class StringIsNullOrEmptyValidationRule : ValidationRule
{
private string _errorMessage = "";
public string ErrorMessage
{
get
{
return _errorMessage;
}
set
{
_errorMessage = value;
}
}
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
ValidationResult result = new ValidationResult(true, null);
if (value == null || ((string)value).Trim() == "")
{
result = new ValidationResult(false, this.ErrorMessage);
}
return result;
}
}
Now I have a datagrid in MainWindow.xaml which is bound to an ObservableCollection called People. Here is my DataGrid :
现在我在 MainWindow.xaml 中有一个数据网格,它绑定到一个名为 People 的 ObservableCollection。这是我的 DataGrid :
<DataGrid x:Name="maindg" ItemsSource="{Binding People}" AutoGenerateColumns="False" SelectionMode="Single" SelectionUnit="CellOrRowHeader">
<DataGrid.Columns>
<DataGridTextColumn Header="First Name" Binding="{Binding FirstName}" />
<DataGridTextColumn Header="Last Name">
<DataGridTextColumn.Binding>
<Binding Path="LastName">
<Binding.ValidationRules>
<local:StringIsNullOrEmptyValidationRule ErrorMessage="LastName is required" />
</Binding.ValidationRules>
</Binding>
</DataGridTextColumn.Binding>
</DataGridTextColumn>
<DataGridTextColumn Header="City" Binding="{Binding City}" />
</DataGrid.Columns>
</DataGrid>
Problem :
问题 :
I kept a breakpoint on StringIsNullOrEmptyValidationRule's Validate Method's first line. When I don't enter any data in a cell under LastName Column, and try to move away from the cell, it does not hit breakpoint, that means validation does not even check.
我在 StringIsNullOrEmptyValidationRule 的 Validate Method 的第一行上保留了一个断点。当我没有在 LastName Column 下的单元格中输入任何数据并尝试离开该单元格时,它不会命中断点,这意味着验证甚至不会检查。
If I enter some data to the cell under lastName column and then try to move away from the cell, it tries to validates the cell. So it hits the breakpoint.
如果我在 lastName 列下的单元格中输入一些数据,然后尝试离开该单元格,它会尝试验证该单元格。所以它遇到了断点。
So, my question is how can I validate NullOrEmpty Cell?
所以,我的问题是如何验证 NullOrEmpty Cell?
回答by Rohit Vats
ValidationRule works only in case property value is changed. But, when you go from empty cell, value has not changed. Hence, validation rule won't fired in that case.
ValidationRule 仅在属性值更改的情况下才起作用。但是,当您从空单元格开始时,值没有改变。因此,在这种情况下不会触发验证规则。
Implement IDataErrorInfoon Person class and do your validation over there something like this:
在 Person 类上实现IDataErrorInfo并在那里进行验证,如下所示:
public class Person : IDataErrorInfo
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string City { get; set; }
public string Error
{
get
{
return String.Concat(this[FirstName], " ", this[LastName], " ",
this[City]);
}
}
public string this[string columnName]
{
get
{
string errorMessage = null;
switch (columnName)
{
case "LastName":
if (String.IsNullOrWhiteSpace(LastName))
{
errorMessage = "LastName is required.";
}
break;
}
return errorMessage;
}
}
}
And in your XAML, you need to set ValidatesOnDataErrorproperty to true for LastName binding:
在您的 XAML 中,您需要将ValidatesOnDataErrorLastName 绑定的属性设置为 true:
<DataGridTextColumn Header="Last Name" Binding="{Binding LastName,
ValidatesOnDataErrors=True}"/>
回答by aguertin
This was retrieved here: http://msdn.microsoft.com/en-us/library/ykdxa0bc(v=vs.90).aspx
这是在此处检索的:http: //msdn.microsoft.com/en-us/library/ykdxa0bc(v=vs.90).aspx
private void dataGridView1_CellValidating(object sender,
DataGridViewCellValidatingEventArgs e)
{
string headerText = dataGridView1.Columns[e.ColumnIndex].HeaderText;
// Abort validation if cell is not in the CompanyName column.
if (!headerText.Equals("CompanyName")) return;
// Confirm that the cell is not empty.
if (string.IsNullOrEmpty(e.FormattedValue.ToString()))
{
dataGridView1.Rows[e.RowIndex].ErrorText =
"Company Name must not be empty";
e.Cancel = true;
}
Basically you can use conditional statements to verify data.
基本上您可以使用条件语句来验证数据。
This is obviously the most standard way of validating that something exists in the cell...
这显然是验证单元格中存在某些东西的最标准方法......

