我有一个TextBox,其绑定在 Mo 属性:
<TextBox>
<TextBox.Style>
<Style TargetType="TextBox">
<Style.Setters>
<Setter Property="Text">
<Setter.Value>
<Binding Path="Mo" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<validator:FloatPositiveValidationRule ValidatesOnTargetUpdated="True" />
</Binding.ValidationRules>
</Binding>
</Setter.Value>
</Setter>
</Style.Setters>
</Style>
</TextBox.Style>
</TextBox>
这个包含一个验证规则,仅当值不为空且大于0时验证控件:
public class FloatPositiveValidationRule : ValidationRule
{
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
string str = (string)value;
if (str.Length > 0)
{
double mo = Double.Parse(str.Replace(".", ","));
if (mo > 0)
return new ValidationResult(true, null);
else
return new ValidationResult(false, "Must be greater than 0");
}
else
return new ValidationResult(false, "Empty");
}
}
在我的视图模型中,当验证为false时,不会触发setter:
private double? _mo;
public string Mo
{
get { return _mo.ToString(); }
set
{
if (value != "")
mo = double.Parse(value.Replace(".", ","));
Set(ref _mo, mo);
}
}
即使验证无效,是否可以输入设置器?
答案 0 :(得分:1)
您可以尝试将ValidationStep
属性设置为UpdatedValue
:
<validator:FloatPositiveValidationRule ValidatesOnTargetUpdated="True" ValidationStep="UpdatedValue" />
这应该在设置了源属性之后运行验证规则。
但你真正应该做的是删除ValidationRule
并在视图模型中实现验证逻辑,例如通过实现INotifyDataErrorInfo接口。