WPF 棱镜 通知属性已更改,但未设置验证



我刚刚开始使用带有 wpf 的棱镜,不明白为什么我的属性没有更新。我有一个绑定到带有验证的文本块,它一直工作到我删除最后一个字符。我浏览了调试器,没有调用 set 属性,而是调用了验证方法。另外,我不明白更新罐头执行方法的工作原理。当我在文本框中输入字符时,它会触发返回 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>

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

改为在命令上调用RaiseCanExecuteChanged。例如,框架调用CanExecute来确定按钮是否已启用。

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

检查此属性,_userImageModel.Title,它将属性设置在那里。此外,保存命令未挂接到文本框。

我找到了解决问题的方法。 就我们使用验证而言,如果值不正确,则不会设置它是合乎逻辑的。可以通过设置验证步骤 = 提交值来避免这种情况。 但是,在那之后,在验证类中,我们不会获取值,而是表达式绑定(要获取值,只需使用此链接上的解决方案 ValidationRule with ValidationStep="UpdateValue" 使用 BindingExpression 而不是更新的值调用

最新更新