首页 > 解决方案 > Wpf prism 通知属性已更改,未设置验证

问题描述

我刚开始在 wpf 中使用棱镜,但不明白为什么我的属性没有更新。我有一个带有验证的文本块绑定,它一直有效,直到我删除最后一个字符。看了下调试器,没有调用set属性,而是调用了验证方法。另外,我不明白更新 can 执行方法是如何工作的。当我在文本框中输入字符时,它会触发返回 true,但删除后它不会更新。我将不胜感激,这是我的代码。

我的视图模型(构造函数中的这个命令)

SaveCommand = new DelegateCommand(ExecuteSaveCommand, CanExecuteSaveCommand);

 public string ImageTitle
 {
      get => _userImageModel.Title;
      set
      {
          _userImageModel.Title = value;
          RaisePropertyChanged(); 
          SaveCommand.CanExecute();
      }
 }

private bool CanExecuteSaveCommand()
{
        var x = string.IsNullOrWhiteSpace(_userImageModel.Title) == false || 
                                              _userImageModel.Title!=null;
        return x;
}

我的验证规则

public class UserImageValidator : ValidationRule
{
    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        if (value == null)
            return new ValidationResult(false,"value cannot be empty");

        if(!(value is string propertyValue))
            return new ValidationResult(false,"exception");

        if(string.IsNullOrWhiteSpace(propertyValue))
            return new ValidationResult(false,"Required");

        return ValidationResult.ValidResult;
    }
}

我的观点

 <TextBox
        Grid.Row="0"
        Grid.Column="1"
        MinWidth="200"
        Margin="5"
        VerticalAlignment="Center"
        MinLines="4"
        Validation.ErrorTemplate="{StaticResource ErrorTemplate}">
        <TextBox.Text>
          <Binding Path="ImageTitle" UpdateSourceTrigger="PropertyChanged">
            <Binding.ValidationRules>
              <validateRule:UserImageValidator />
            </Binding.ValidationRules>
          </Binding>
        </TextBox.Text>
      </TextBox>

标签: c#wpfxamlprism

解决方案


我不明白更新 can 执行方法是如何工作的。

RaiseCanExecuteChanged您改为调用命令。例如,框架调用CanExecute以确定按钮是否启用。

另外,string.IsNullOrWhiteSpace(_userImageModel.Title) == false || _userImageModel.Title!=null没有多大意义(!= null对于空格字符串来说是真的),你的意思是!string.IsNullOrWhiteSpace( _userImageModel.Title )


推荐阅读