【发布时间】:2020-06-23 22:42:34
【问题描述】:
我刚开始在 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>
【问题讨论】: