WPF简单验证问题 - 设置自定义的ErrorContent

12
如果我有以下的文本框:

If I have the following TextBox:

<TextBox Height="30" Width="300" Margin="10" Text="{Binding IntProperty, 
       NotifyOnValidationError=True}" Validation.Error="ContentPresenter_Error">
</TextBox>

在codebehind中,代码如下:

private void ContentPresenter_Error(object sender, ValidationErrorEventArgs e) {
   MessageBox.Show(e.Error.ErrorContent.ToString());
}

如果我在文本框中输入字母"x",弹出的消息是:

无法转换值'x'

有没有一种方法可以自定义这个消息?


为什么不直接在MessageBox.Show();中输入你自己的字符串呢? - Terrance
因为我可能有许多其他文本框,所以最好有一个验证错误处理程序,它只获取最新验证错误的错误内容。 - Adam Rackis
2个回答

11

我不喜欢回答自己的问题,但看起来唯一的方法是实现一个ValidationRule,如下所示(可能存在一些错误):

public class BasicIntegerValidator : ValidationRule {       

    public string PropertyNameToDisplay { get; set; }
    public bool Nullable { get; set; }
    public bool AllowNegative { get; set; }

    string PropertyNameHelper { get { return PropertyNameToDisplay == null ? string.Empty : " for " + PropertyNameToDisplay; } }

    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo) {
        string textEntered = (string)value;
        int intOutput;
        double junkd;

        if (String.IsNullOrEmpty(textEntered))
            return Nullable ? new ValidationResult(true, null) : new ValidationResult(false, getMsgDisplay("Please enter a value"));

        if (!Int32.TryParse(textEntered, out intOutput))
            if (Double.TryParse(textEntered, out junkd))
                return new ValidationResult(false, getMsgDisplay("Please enter a whole number (no decimals)"));
            else
                return new ValidationResult(false, getMsgDisplay("Please enter a whole number"));
        else if (intOutput < 0 && !AllowNegative)
            return new ValidationResult(false, getNegativeNumberError());

        return new ValidationResult(true, null);
    }

    private string getNegativeNumberError() {
        return PropertyNameToDisplay == null ? "This property must be a positive, whole number" : PropertyNameToDisplay + " must be a positive, whole number";
    }

    private string getMsgDisplay(string messageBase) {
        return String.Format("{0}{1}", messageBase, PropertyNameHelper);
    }
}

你可能接受自己的答案:我搜索了很长时间,但并没有找到其他解决方案。 - stijn
1
那就这样吧 - 至少在有更好的东西出现之前 :) - Adam Rackis

6

您可以使用ValidationRules。

例如,在我的情况下,当用户在十进制datagridtextcolumn中输入无效值时,我可以使用以下内容覆盖默认消息“无法转换值”:

<DataGridTextColumn x:Name="Column5" Header="{x:Static p:Resources.Waste_perc}" Width="auto">
    <DataGridTextColumn.Binding>
        <Binding Path="Waste" ValidatesOnDataErrors="True" UpdateSourceTrigger="LostFocus">
            <Binding.ValidationRules>
                <myLib:DecimalRule />
            </Binding.ValidationRules>
        </Binding>
    </DataGridTextColumn.Binding>
</DataGridTextColumn>

以下是DecimalRule的代码:

public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
    decimal convertedDecimal;
    if (!decimal.TryParse((string)value, out convertedDecimal))
    {
        return new ValidationResult(false, "My Custom Message"));
    }
    else
    {
        return new ValidationResult(true, null);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接