c# - PropertyChangedEvent 和 CanExecute 问题

标签 c# wpf mvvm prism wpf-4.0

我正在使用 MVVM (prism) 开发 wpf 应用程序。

我的模型类之一“StandardContact”的属性直接绑定(bind)到 View 。我使用 IDataErrorInfo 来跟踪和通知模型是否有任何错误。如果模型中有任何错误,我会禁用“保存”命令。

当用户输入一些数据时,我使用 StandardContact.PropertyChanged 处理程序来查看“保存”命令是否可以执行(即用户输入的模型数据是否有效)。问题在于 StandardContact.PropertyChanged 处理程序在 IDataErrorInfo 的验证代码之前被调用,因此“保存”命令的 CanExecute 不能正确反射(reflect)该命令是否可以执行。我正在寻找的是,在 CanExecute 执行之前,应该运行 IDataErrorInfo 验证,以便 CanExecute 将查询模型中的最新数据并决定是否启用它。这是我正在使用的示例代码

型号:

public class StandardContact :EntityBase, IDataErrorInfo
{
    public virtual string Name 
    {
        get { return _name; }
        set { SetField(ref _name, value, () => Name); }
    }

    //...
    //Validators
    public string this[string propertyName] 
    {
        get 
        {
            string error = null;
        //....
    }

View 模型

public class SContactEditViewModel : NotificationObject, INavigationAware 
{
    //....
        StandardContact.PropertyChanged += 
            new PropertyChangedEventHandler(StandardContact_PropertyChanged);

    void StandardContact_PropertyChanged(object sender, PropertyChangedEventArgs e) 
    {
        //Requery if command can execute
        SaveNewCommand.RaiseCanExecuteChanged(); 
    }
}

最佳答案

我刚刚检查了我们专有的 MVVM 库。在 ViewModels 索引器(在您的例子中是模型索引器)中,验证请求的属性:

public string this[string propertyName]
{
    get
    {
        string result = null;

        if (CanDataErrorValidated(propertyName))
        {
            int errorCount = CurrentValidationAdapter.ErrorCount();
            result = ValidateProperty(propertyName, GetValidateValue(propertyName));

            // if the error flag has been changed after validation
            if (errorCount != CurrentValidationAdapter.ErrorCount())
            {
                RaisePropertyChanged(PropHasError);
                RaisePropertyChanged(PropError);
            }
        }
        else
        {
            RaisePropertyChanged(PropHasError);
            RaisePropertyChanged(PropError);
        }

        return result;
    }
}

因此您的问题的解决方案似乎可以即时验证请求的属性。

关于c# - PropertyChangedEvent 和 CanExecute 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10201325/

相关文章:

c# - 从哈希表中读取匹配的记录到类对象中

c# - 将数据模板和样式放置到生成的按钮

java - DiffCallBack不被调用吗?

c# - 通过绑定(bind)在鼠标单击时导航 WebBrowser

c# - 反序列化单个对象

c# - 无效方差 : The type parameter must be invariantly valid but is covariant

c# - 从 .Net Framework 4.7 升级到 4.8 后使用 MSBuild 发布项目时出错

wpf - 将 UserControl 属性公开给 XAML

wpf - WPF:持续时间不确定的进度条?

c# - WPF 数据模板和自动创建的 viewModel 对象