【问题标题】:Validation.error event in event command事件命令中的 Validation.error 事件
【发布时间】:2013-07-01 07:53:59
【问题描述】:

我有一个文本框:

    <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>

我的 ViewModel 如下所示:

  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
}

当我在后面的代码中捕获事件 Validation.Error 时:

但是当我尝试以这种方式运行它时,事件命令没有提供有效的功能。

我错过了什么吗?

【问题讨论】:

    标签: wpf events mvvm binding eventtocommand


    【解决方案1】:

    由于Validation.Error附加事件,那么它不能正常与EventToCommand一起使用。

    您将在以下链接中找到答案:

    EventToCommand with attached event

    【讨论】:

      【解决方案2】:

      TextBox 没有 Validation.Error 事件。此外,System.Controls.TextBox(您正在使用)没有 Validating 事件。

      使用 LostFocus 验证文本框,如果您想使用 MVVM 模式验证,请参阅 this question

      【讨论】:

      • 确实,文本框有Validation.Error。看看有问题的图片。它在代码背后工作。我对失去焦点不感兴趣 - 验证已经在工作。我想在发生验证错误时运行命令。
      • 不,TextBox 没有 Validation.Error 事件。您试图将其用作事件,这是错误的。
      • 当这在代码背后 - 这不是一个事件?
      • Validation.Error 附加事件:msdn.microsoft.com/en-us/library/…
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多