wpf mvvm 错误验证

标签 wpf validation error-handling

我有一个简单的 wpf 应用程序,如果表单有错误,我会尝试停用保存按钮。

问题是,虽然验证看起来很完美,但我不知道为什么,但我总是从负责检查错误的方法中得到错误。

让我通过提供代码更清楚地说明。

这是 MainWindow.Xaml.cs 中的代码

private readonly HashSet<ValidationError> errors = new HashSet<ValidationError>();
    private Lazy<MainWindowViewModel> viewModel;

    public MainWindow() {
        InitializeComponent();
        InitializeValidaton();
    }

    void InitializeValidaton() {
        viewModel = new Lazy<MainWindowViewModel>();
        Validation.AddErrorHandler(this, ErrorChangedHandler);
    }

    private void ErrorChangedHandler(object sender, ValidationErrorEventArgs e) {
        if (e.Action == ValidationErrorEventAction.Added) {
            errors.Add(e.Error);
        } else {
            errors.Remove(e.Error);
        }
        //I set a breakpoint here and it returns the correct value. False if it has errors  and True if not
        viewModel.Value.IsValid = !errors.Any();

    }

这是按钮的命令
 public ICommand SaveItem {
        get { return new RelayCommand(SaveItemExecute,CanSaveItem); }
    }
 private bool CanSaveItem() {
        return IsValid;
    }

  //I set up here a breakpoint and it returns the correct value just once.
  //The application looked up on CanSaveItem all the time and except the first time, it returns wrong value
  private bool _isValid;
    public bool IsValid {
        get { return _isValid; }
        set {
            _isValid = value;
            RaisePropertyChanged("IsValid");
  }
    }

验证规则
[Required(ErrorMessage = "Please enter Title")]
    [StringLength(100, ErrorMessage = "The maximum length is 100")]
    string Name { get; set; }

我不知道这是否有意义,但我要停用的按钮位于 UserControl 中。

我不明白为什么 userControl 中的 canExecute 方法会多次触发。无论我用什么方法,它都有相同的 react 。我提到了 userControl,因为如果我在主窗口中使用相同的方法(在 ICommand 的一部分中),它只会触发一次

如果有人能帮我解决这个问题,我将不胜感激。

谢谢

最佳答案

我宁愿发布一个使用您的模型进行验证的工作示例。根据需要调整此示例,您可能会发现产生错误工作的差异。

MainWindow.xaml

<StackPanel>
    <TextBox x:Name="ValidatedTextBox" Width="200">
        <TextBox.Text>
            <Binding Path="EnteredText" UpdateSourceTrigger="PropertyChanged" NotifyOnValidationError="True">
                <Binding.ValidationRules>
                    <local:NotEmptyInputRule ValidatesOnTargetUpdated="True" />
                </Binding.ValidationRules>
            </Binding>
        </TextBox.Text>
    </TextBox>
    <Button Content="Save" Width="60" IsEnabled="{Binding IsValid}" />
</StackPanel>

房产 EnteredText必须存在于 ViewModel 中:
class MainWindowViewModel : INotifyPropertyChanged
{
    public ICommand SaveItem
    {
        get { return new SimpleCommand(SaveItemExecute, CanSaveItem); }
    }

    public void SaveItemExecute()
    {
        //save
    }

    private bool CanSaveItem()
    {
        return IsValid;
    }

    //I set up here a breakpoint and it returns the correct value just once.
    //The application looked up on CanSaveItem all the time and except the first time, it returns wrong value
    private bool _isValid;
    public bool IsValid
    {
        get { return _isValid; }
        set
        {
            _isValid = value;
            OnPropertyChanged("IsValid");
        }
    }

    public string EnteredText { get; set; }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        if (this.PropertyChanged != null)
        {
            this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

}

并且不要忘记设置DataContext在主窗口中。
    public MainWindow()
    {
        InitializeComponent();
        InitializeValidaton();
        this.DataContext = viewModel.Value;
    }

还有Command类和验证规则。
public class SimpleCommand : ICommand
{
    /// <summary>
    /// Gets or sets the Predicate to execute when the CanExecute of the command gets called
    /// </summary>
    public Predicate<object> CanExecuteDelegate { get; set; }

    /// <summary>
    /// Gets or sets the action to be called when the Execute method of the command gets called
    /// </summary>
    public Action<object> ExecuteDelegate { get; set; }

    public SimpleCommand(Action execute, Func<bool> canExecute)
    {
        this.ExecuteDelegate = _ => execute();
        this.CanExecuteDelegate = _ => canExecute();
    }

    #region ICommand Members

    /// <summary>
    /// Checks if the command Execute method can run
    /// </summary>
    /// <param name="parameter">THe command parameter to be passed</param>
    /// <returns>Returns true if the command can execute. By default true is returned so that if the user of SimpleCommand does not specify a CanExecuteCommand delegate the command still executes.</returns>
    public bool CanExecute(object parameter)
    {
        if (CanExecuteDelegate != null)
            return CanExecuteDelegate(parameter);
        return true;// if there is no can execute default to true
    }

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    /// <summary>
    /// Executes the actual command
    /// </summary>
    /// <param name="parameter">THe command parameter to be passed</param>
    public void Execute(object parameter)
    {
        if (ExecuteDelegate != null)
            ExecuteDelegate(parameter);
    }

    #endregion

}
class NotEmptyInputRule : ValidationRule
{
    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        if (value != null)
        {
            string input = value as string;

            if (input.Length > 0)
                return new ValidationResult(true, null);
        }

        return new ValidationResult(false, "Validation error. Field input required.");
    }
}

关于wpf mvvm 错误验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4884595/

相关文章:

javascript - ASP.NET MVC 客户端验证

python - Selenium RC : how to capture/handle error?

error-handling - “NSError”无法转换为 'AutoreleasingUnsafePointer<NSError?>'

wpf - 设置 WPF RichTextBox 中特定文本行的格式

c# - 当 ViewModel 改变时如何让 View 更新

javascript - Validate.js 不显示错误

c - 我们应该检查内存分配是否失败吗?

c# - 如何在ListView WPF中将命令绑定(bind)到复选框?

c# - 理解调度队列

ruby-on-rails - Rails 验证数组中的值