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

mat*_*att 4 c# data-binding validation wpf

我希望能够覆盖默认的文本框转换验证并自己处理。我查看了验证规则,但无法让它禁用原始验证。到目前为止的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>
Run Code Online (Sandbox Code Playgroud)

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

mm8*_*mm8 5

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

ValidationRule请参考这里的答案,了解如何使用自定义自定义错误消息的示例:

如何处理 DependencyProperty 溢出情况?

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

<Window.Resources>
    <local:YourConverter x:Key="conv" />
</Window.Resources>
...
<TextBox Text="{Binding Path=Option.Value, NotifyOnSourceUpdated=True, Coverter={StaticResource conv}}" / >
Run Code Online (Sandbox Code Playgroud)
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());
    }
}
Run Code Online (Sandbox Code Playgroud)