2012-05-15 5 views
0

Я хочу уведомить ошибки проверки, когда я вношу неверный ввод в строки DataGrid.Интерфейс IDataErrorInfo() в WPF MVVM

<DataGridTextColumn Header="Name" Binding="{Binding Path=Name, ValidatesOnDataErrors=True, ValidatesOnExceptions=True}"/> 
<DataGridTextColumn Header="Age" Binding="{Binding Path=Age}"/> 
<DataGridTextColumn Header="Date Of Birth" Binding="{Binding Path=DateOfBirth, ValidatesOnDataErrors=True, ValidatesOnExceptions=True, NotifyOnValidationError=True}"/> 

Я реализовал IDataErrorInfo в ViewModel со следующим свойством.

public string this[string propname] 
     { 
      get 
      { 
       switch (propname) 
       { 
        case "Age": 
         int age=0; 
         if (int.TryParse("Age", out age)) 
         { 
          if (age <= 0 && age > 99) 
          { 
           return "Please enter the valid Age..."; 
          } 
         } 
         else 
          return "Please enter the valid Age..."; 

         break; 
        case "Name": 
         if (string.IsNullOrEmpty("Name")) 
         { 
          return "Enter the valid Name"; 
         } 
         break; 
        case "Address": 
         if (string.IsNullOrEmpty("Address")) 
         { 
          return "Enter the valid Address"; 
         } 
         break; 
        case "DateOfBirth": 
         DateTime datetime; 
         if (!DateTime.TryParse("DateOfBirth", out datetime)) 
         { 
          return "Please enter the valid Date of Birth"; 
         } 
         break; 
       } 
       return string.Empty; 
      } 
     } 

Но проверки не произошло. Мне нужно требование, чтобы, если я набираю текст в свойство DateTime в DataGridCell, должен быть красный шар, чтобы указать ошибку проверки.

Возможно ли это? .. Кто-нибудь?

ответ

3

Эта линия:

if (int.TryParse("Age", out age)) 

не может быть правильным.

Если вы хотите красный шар, чтобы показать вам нужно обеспечить красный шар:

<Style x:Key="TextBlockStyle" TargetType="{x:Type TextBlock}"> 
    <Style.Triggers> 
     <Trigger Property="Validation.HasError" Value="true"> 
      <Setter Property="ToolTip" 
        Value="{Binding RelativeSource={RelativeSource Self}, 
        Path=(Validation.Errors)[0].ErrorContent}"/> 
     </Trigger> 
    </Style.Triggers> 
</Style> 

И:

<DataGridTemplateColumn.CellTemplate> 
    <DataTemplate> 
     <TextBlock Style="{StaticResource ResourceKey=TextBlockStyle}" 
        Text="{Binding Path=Name, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, NotifyOnValidationError=True}"/> 
    </DataTemplate> 
</DataGridTemplateColumn.CellTemplate> 

Я оставляю вам, чтобы сделать его красным.