禁用并处理 WPF 文本框上的“无法转换值”验证错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42974642/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 14:03:14  来源:igfitidea点击:

Disable and handle 'Value could not be converted' validation error on WPF textbox

c#wpfvalidationdata-binding

提问by matt

I want to be able to override the default textbox validation for convertion and handle it myself. I've looked at validation rules but I can't get it to disable the original validation. Xaml so far:

我希望能够覆盖转换的默认文本框验证并自己处理。我查看了验证规则,但无法禁用原始验证。Xaml 到目前为止:

<Grid>
    <TextBox Text="{Binding Path=Option.Value, NotifyOnSourceUpdated=True}" >
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="SourceUpdated">
                <i:InvokeCommandAction Command="{Binding OptionValueChanged}"></i:InvokeCommandAction>
       </i:EventTrigger>
        </i:Interaction.Triggers>
    </TextBox>
</Grid>

Atm, when a string is entered it displays 'Value {val} cannot be converted' as the field is an integer. How can this be disabled to handle the value myself?

Atm,当输入一个字符串时,它显示“值 {val} 无法转换”,因为该字段是一个整数。如何禁用它以自己处理值?

采纳答案by mm8

An intproperty can only be set to an intvalue and nothing else. You could customize the error message but you won't ever be able to set the intproperty to something else than an int.

一个int属性只能设置为一个int值,而不是其他。您可以自定义错误消息,但您永远无法将该int属性设置为int.

Please refer to the answer here for an example of how to use a custom ValidationRuleto customize the error message:

请参阅此处的答案以获取如何使用自定义ValidationRule来自定义错误消息的示例:

How do I handle DependencyProperty overflow situations?

如何处理 DependencyProperty 溢出情况?

If you want to handle the actual conversion between the stringand the intyourself you could use a converter:

如果您想处理string和之间的实际转换,int您可以使用转换器:

<Window.Resources>
    <local:YourConverter x:Key="conv" />
</Window.Resources>
...
<TextBox Text="{Binding Path=Option.Value, NotifyOnSourceUpdated=True, Coverter={StaticResource conv}}" / >


public class YourConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        //convert the int to a string:
        return value.ToString();
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        //convert the string back to an int here
        return int.Parse(value.ToString());
    }
}