Seekeer
Seekeer

Reputation: 1394

Validating two properties in WPF

I have class with such properties:

    public DateTime Start { get; set; }
    public DateTime Finish { get; set; }

And such ViewModel:

    <StackPanel>
        <DatePicker SelectedDate="{Binding Start}" />
        <DatePicker SelectedDate="{Binding Finish}" />
    </StackPanel>

I want to enable validation. So, when Start > Finish there must be error. What is the simplest way to provide such validation?

Upvotes: 1

Views: 2148

Answers (3)

Seekeer
Seekeer

Reputation: 1394

Well, I've found answer myself) I extended my TimeRange class to implement IDataErrorInfo interface like this:

public class TimeRange : IDataErrorInfo
{
    public DateTime Start { get; set; }
    public DateTime Finish { get; set; }


    #region IDataErrorInfo Members

    public string Error
    {
        get { throw new NotImplementedException(); }
    }

    private bool _IsValid()
    {
        return Finish > Start;
    }

    public string this[string columnName]
    {
        get
        {
            string result = null;
            if (columnName == "Start" && !_IsValid())
                result = "Start must occure before Finish!";
            else if (columnName == "Finish" && !_IsValid())
                result = "Finish must occure after Start!";
            return result;
        }
    }

    #endregion
}

And then change my xaml code to:

        <DatePicker SelectedDate="{Binding Start, UpdateSourceTrigger=LostFocus, 
            ValidatesOnDataErrors=true, NotifyOnValidationError=true}" />
        <DatePicker SelectedDate="{Binding Finish, UpdateSourceTrigger=LostFocus,
            ValidatesOnDataErrors=true, NotifyOnValidationError=true}" />

Upvotes: 4

jrb
jrb

Reputation: 1728

Compare the values on get. If Start>Finish return null or something.

Upvotes: -2

K Mehta
K Mehta

Reputation: 10533

You can use Binding.ValidationRules.

You can find a MSDN sample here.

Upvotes: 2

Related Questions