noaRAVE
noaRAVE

Reputation: 432

Silverlight control's input validation

I want to implement two types of validation in my silverlight application. I want "business-logic" rules to be implemented in viewmodel(like end date is not earlier than start date) which i have already accomplished, and input validation somewhere on main control, where input fields are(like date is in bad format). Is there anything silverlight can "help" me with? I mean there is at least UnsetValue there for me, but is there any event associated or i have to catch all OnChanged events? Also is there a way to manually display red border around control when i want to?

Sorry, it was not obvious from my question, but i finished with the part that includes "business-logic" rules - my viewmodel indeed implements INotifyDataErrorInfo, i'm troubled with second type of validation.

Upvotes: 0

Views: 820

Answers (2)

Rumplin
Rumplin

Reputation: 2768

Implement INotifyDataErrorInfo on your properties

then on your property that is binded in XAML use a friendly display name:

private DateTime? _datumP = DateTime.Now;
[Display(Name = "Date", ResourceType = typeof(CommonExpressions))]
public DateTime? DatumP
{
    get
    {
        return _datumP;
    }
    set
    {
        if (_datumP != value)
        {
            _datumP = value;
            RaisePropertyChanged(DatumPonudbePropertyName);
        }

        ValidateDate(DatumPonudbe, DatumPonudbePropertyName);
    }
}

Then your method to validate dates:

 public void ValidateDate(DateTime? value, string propertyName)
 {
     RemoveError(propertyName, CommonErrors.DatumNull_ERROR);

     if (value == null)
         AddError(propertyName, CommonErrors.DatumNull_ERROR, false);

 }

And now for the XAML part:

<sdk:DatePicker Width="100" SelectedDate="{Binding DatumP, Mode=TwoWay, 
                            NotifyOnValidationError=True, ValidatesOnNotifyDataErrors=True, 
                            ValidatesOnDataErrors=True, ValidatesOnExceptions=True}" />

P.S.

CommonExpressions and CommonErrors are my Resource files for multilanguage, you can use plain strings here.

Upvotes: 0

Bas
Bas

Reputation: 27095

Implement INotifyDataErrorInfo on your ViewModel to enable validation on View Model level.

Upvotes: 2

Related Questions