English 中文(简体)
WPF简单验证问题-设置自定义ErrorContent
原标题:WPF Simple Validation Question - setting custom ErrorContent
  • 时间:2011-05-27 14:01:10
  •  标签:
  • c#
  • wpf

如果我有以下文本框:

<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

是否有自定义此消息的方法?

最佳回答

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

您可以使用ValidationRules。

例如,在我的情况下,当用户在十进制datagridtext列中输入无效值时,我可以用以下内容覆盖它,而不是默认消息“value could not be converted”:

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




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签