【问题标题】:WPF Simple Validation Question - setting custom ErrorContentWPF 简单验证问题 - 设置自定义 ErrorContent
【发布时间】:2011-05-27 14:01:10
【问题描述】:

如果我有以下文本框:

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

这在代码隐藏中:

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

如果我在文本框中输入字母“x”,弹出的信息是

值“x”无法转换

有没有办法自定义这条消息?

【问题讨论】:

  • 为什么不把你自己的字符串放在 MessageBox.Show(); 中?
  • 因为我可能有很多其他的文本框,如果有一个验证错误处理程序只接受最新验证错误的错误内容,那就太好了。

标签: c# wpf


【解决方案1】:

我不喜欢回答我自己的问题,但似乎唯一的方法是实现一个 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);
    }
}

【讨论】:

  • 你可能会接受你自己的答案:我搜索了很长时间,但没有找到比这更多的解决方案..
  • 就这样吧——至少在有人提出更好的东西之前:)
【解决方案2】:

您可以使用 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);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多