Search code examples
wpfeventsmvvmbindingeventtocommand

Validation.error event in event command


I have a text box:

    <TextBox Height="20" Width="150" Text="{Binding MyProperty,NotifyOnValidationError=True,ValidatesOnDataErrors=True}" >
          <i:Interaction.Triggers>
          <i:EventTrigger EventName="Validation.Error">
                <mvvm:EventToCommand Command="{Binding MyCmd}" PassEventArgsToCommand="True" ></mvvm:EventToCommand>
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </TextBox>

My ViewModel looks like this:

  public class MyViewModel : ValidationViewModelBase, INotifyPropertyChanged
{
    private int myVar;

    [Range(0, 10)]
    public int MyProperty
    {
        get { return myVar; }
        set
        {
            myVar = value;
            OnPropertyChanged("MyProperty");
        }
    }



    public MyViewModel()
    {
        MyCmd = new RelayCommand<RoutedEventArgs>(Valid);
    }

    public RelayCommand<RoutedEventArgs> MyCmd { get; set; }

    private void Valid(RoutedEventArgs args)
    {
        //Do something
    }

    #region INotifyPropertyChanged

    public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged(string name)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(name));
        }
    }

    #endregion INotifyPropertyChanged
}

When I catch the event Validation.Error in Code Behind it works:

enter image description here

But when I try to run it this way with the Event Command is not coming Valid function.

Did I miss something?


Solution

  • Since Validation.Error is Attached Event, then it does not work with EventToCommand normally.

    The answer you will find at the link below:

    EventToCommand with attached event