当验证规则无效时,WPF MVVMLight Setter 未在绑定 TextBox 上触发

WPF MVVMLight Setter not fired on binding TextBox when validation rule is invalid

我有一个在 Mo 属性 上绑定的 TextBox :

<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");
    }
}

在我的视图模型中,当验证为假时,不会触发 setter :

private double? _mo;
public string Mo
{
    get { return _mo.ToString(); }

    set
    {
        if (value != "")
            mo = double.Parse(value.Replace(".", ","));

        Set(ref _mo, mo);
    }
}

是否可以输入setter即使验证无效?

您可以尝试将 ValidationStep 属性 设置为 UpdatedValue:

<validator:FloatPositiveValidationRule ValidatesOnTargetUpdated="True" ValidationStep="UpdatedValue"  />

这应该使验证规则 运行 源 属性 设置之后。

但您真正应该做的是删除 ValidationRule 并在您的视图模型中实现验证逻辑,例如通过实现 INotifyDataErrorInfo 接口。