1

I'm on a project Csharp MVVM and I would like to know if it was possible to use Data.Annotations directment in models , not ViewModels . If so how ?

I thought like that, My Model (class Ticket):

 [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; }

My ViewModel (use IDataErrorInfo):

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

And my View

 <!-- 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}"/>  

But it doesn't work...

Tseng
  • 61,549
  • 15
  • 193
  • 205
Camille Colvray
  • 420
  • 3
  • 16
  • Don't use models directly in your views, it creates tight coupling from View and Model. The main purpose of MVVM is decouple them. – Tseng Mar 30 '16 at 12:44
  • Ok so i have to separated properties of my Model in my viewModel and use data annotations it that. But using an orm(dapper) I must , at a given moment it together in an object ? example: cnn.Insert(myObject). i could do like that each time , new Item{ prop = my separate property....} so if i have so much fields.... – Camille Colvray Mar 30 '16 at 12:55

1 Answers1

0

You have to implement the IDataErrorInfo interface on the Ticket class. Then in the indexed property this[string propertyName] you can use Validator.TryValidateProperty method and a 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;
        }
    }
}
Il Vic
  • 5,576
  • 4
  • 26
  • 37
  • I thank you I opted for all your solution works very well! but the problem is that with the validation by default, it just make controls in addition to my management Error! example, on a blocking me decimal points or point and shows me an error message saying, the value can not be converted. But I've never create this message! how would you remove? – Camille Colvray Apr 08 '16 at 06:59
  • Without your code @CamilleColvray it is hard to say something. Maybe this [question](http://stackoverflow.com/questions/6123880/how-to-handle-exception-in-value-converter-so-that-custom-error-message-can-be-d) can help you with your new issue. Otherwise you should post your code (maybe in a new question) – Il Vic Apr 08 '16 at 08:47