我刚开始使用带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>
答案 0 :(得分:0)
我不知道如何更新罐执行方法。
您改为在命令上调用RaiseCanExecuteChanged
。框架调用CanExecute
来确定是否启用了按钮。
此外,string.IsNullOrWhiteSpace(_userImageModel.Title) == false || _userImageModel.Title!=null
并没有多大意义(!= null
对于空格字符串而言是正确的),您是说!string.IsNullOrWhiteSpace( _userImageModel.Title )
吗?
答案 1 :(得分:0)
检查此属性_userImageModel.Title,在此处设置该属性。另外,SaveCommand也不会挂钩到文本框。
答案 2 :(得分:0)
我找到了解决问题的方法。 就我们使用验证而言,合乎逻辑的是,如果该值不正确,则不会设置它。可以通过将验证步骤设置为“承诺值”来避免这种情况。 但是,此后,在验证类中,我们将不会获取值,而是表达式绑定(要获取值,只需在此链接ValidationRule with ValidationStep="UpdatedValue" is called with BindingExpression instead of updated value上使用解决方案