2016-03-30 29 views
1

我在一個項目Csharp MVVM,我想知道是否有可能在模型中使用Data.Annotations,而不是ViewModels。如果是這樣如何?如何直接在模型中使用數據註釋

我想這樣的, 我的模型(類票):

[Dapper.Key] 
[Required(ErrorMessage = "This field is requierd")] 
[Range(1, int.MaxValue, ErrorMessage ="Only Int")] 
public int? Tic_Id { get; set; } 

[Required(ErrorMessage = "This field is requierd")] 
public DateTime Tic_Date { get; set; } 

我的視圖模型(使用IDataErrorInfo的):

[RaisePropertyChanged] 
    public virtual Ticket FicheItem {get;set;} 

而且我查看

<!-- ID --> 
     <TextBlock Grid.Row="1" Text="ID :" Style="{StaticResource FicheLabelStyle}"/> 
     <TextBox Name="ID" Grid.Row="1" Grid.Column="1" 
        IsEnabled="True" 
        Text="{Binding FicheItem.Tic_Id, UpdateSourceTrigger=PropertyChanged,ValidatesOnDataErrors=True,NotifyOnValidationError=True,Mode=TwoWay}" 
        Style="{StaticResource FicheTextboxStyleNumber}"/> 
     <TextBlock Grid.Column="1" Grid.Row="2" Name="IDError" Text="{Binding (Validation.Errors)[0].ErrorContent, ElementName=ID}" Foreground="Red" Margin="19,3,0,0" 
        Visibility="{Binding ElementName=IDError, Path=Text,Converter={StaticResource FicheErrorVisibilityConverter},Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/> 


     <!-- Date --> 
     <TextBlock Grid.Row="3" Text="Date :" Style="{StaticResource FicheLabelStyle}"/> 
     <TextBox Grid.Row="3" Grid.Column="1" Name="Date" 
       Text="{Binding FicheItem.Tic_Date, ValidatesOnDataErrors=True, NotifyOnValidationError=True,UpdateSourceTrigger=PropertyChanged}" 
       Style="{StaticResource FicheTextboxStyleText}" /> 
     <TextBlock Grid.Column="1" Grid.Row="4" Name="DateError" Text="{Binding (Validation.Errors)[0].ErrorContent, ElementName=Date}" Foreground="Red" Margin="19,3,0,0" 
        Visibility="{Binding ElementName=DateError, Path=Text,Converter={StaticResource FicheErrorVisibilityConverter},Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/> 

但不起作用...

+0

不要直接在視圖中使用模型,它會從視圖和模型創建緊密耦合。 MVVM的主要目的是分離它們。 – Tseng

+0

好的,所以我必須在我的viewModel中分離我的模型的屬性並使用它的數據註釋。但是,在一個特定的時刻,我必須使用一個orm(dapper),它必須在一個對象中?例如:cnn.Insert(myObject)。 我可以這樣做,每次,新項目{prop =我的獨立屬性....}所以,如果我有這麼多的領域...... –

回答

0

您必須在Ticket類上實現IDataErrorInfo接口。然後在索引屬性this[string propertyName]中,您可以使用Validator.TryValidateProperty方法和ValidationContext

public class Ticket : IDataErrorInfo 
{ 
    [Required(ErrorMessage = "This field is required")] 
    [Range(1, int.MaxValue, ErrorMessage = "Only Int")] 
    public int? Tic_Id { get; set; } 

    [Required(ErrorMessage = "This field is required")] 
    public DateTime? Tic_Date { get; set; } 

    string IDataErrorInfo.Error 
    { 
     get 
     { 
      /* It can be improved */   
      return String.Empty; 
     } 
    } 

    string IDataErrorInfo.this[string propertyName] 
    { 
     get 
     { 
      Type objectType = GetType(); 
      PropertyInfo propertyInfo = objectType.GetProperty(propertyName); 
      object propertyValue = propertyInfo.GetValue(this, null); 
      List<System.ComponentModel.DataAnnotations.ValidationResult> results 
       = new List<System.ComponentModel.DataAnnotations.ValidationResult>(); 

      ValidationContext validationContext = 
       new System.ComponentModel.DataAnnotations.ValidationContext(this, null, null); 
      validationContext.MemberName = propertyName; 

      return Validator.TryValidateProperty(propertyValue, validationContext, results) ? 
       String.Empty : results[0].ErrorMessage; 
     } 
    } 
} 
+0

我感謝你我選擇了所有的解決方案作品非常好!但問題在於,在默認情況下進行驗證時,除了我的管理錯誤之外,它只是進行控制。例如,阻止我輸入小數點或點,並向我顯示錯誤消息,說明該值無法轉換。但我從來沒有創造這個信息!你將如何刪除? –

+0

沒有你的代碼@CamilleColvray很難說點什麼。也許這[問題](http://stackoverflow.com/questions/6123880/how-to-handle-exception-in-value-converter-so-that-c​​ustom-error-message-can-be-d)可以幫助你與你的新問題。否則,你應該發佈你的代碼(也許在一個新的問題) –

相關問題