2014-07-10 76 views
3

我想驗證DataGrid中的單元格。這是我第一次驗證的方法。由於我是新手,因此我在驗證中遇到了一些問題。如何驗證DataGrid中的空單元或空單元格

我創建了一個名爲StringIsNullOrEmptyValidationRule.cs的類。此類檢查,如果字符串爲null或「」

這裏是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; 
    } 
} 

現在我有MainWindow.xaml一個DataGrid被綁定到一個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> 

問題:

我一直在StringIsNullOrEmptyValidationRule的validate方法的第一行設置一個斷點。 當我在LastName Column下的單元格中沒有輸入任何數據時,嘗試遠離單元格時,它不會觸及斷點,這意味着驗證甚至不檢查。

如果我將某些數據輸入到lastName列下的單元格,然後嘗試移開單元格,它會嘗試驗證單元格。所以它達到了斷點。

所以,我的問題是我如何驗證NullOrEmpty單元?

+0

如果有人認爲我使用過時的驗證方法,那麼請提出新的方法。 – Vishal

回答

4

有效性規則只適用的情況下,屬性值被改變。但是,當你從空單元走,價值沒有改變。因此,在這種情況下,驗證規則不會被解僱。

落實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; 
     } 
    } 
} 

而在你的XAML,你需要ValidatesOnDataError屬性設置爲true名字綁定:

<DataGridTextColumn Header="Last Name" Binding="{Binding LastName, 
              ValidatesOnDataErrors=True}"/> 
+0

人員類是由實體框架自動生成的。我仍然應該使用您建議的相同方法嗎? – Vishal

+0

是的,你可以使用EF生成的類。 –

+2

鏈接[here](http://blogs.msdn.com/b/bethmassi/archive/2009/07/07/implementing-validation-in-wpf-on-entity-framework-entities.aspx)可能是你的興趣也是如此。 –

1

這是在這裏獲得: 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; 
} 

基本上你可以使用條件語句來驗證數據。

這顯然是驗證的東西在細胞中存在的最標準的方式...

+0

感謝您的努力。對不起,我忘了在提問中提到我很想得到一個MVVM友好的答案。 – Vishal

+0

您提供的解決方案也適用於Winforms。 – Vishal

相關問題