WPF MVVM文本框验证 [英] WPF MVVM Textbox Validation

查看:95
本文介绍了WPF MVVM文本框验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用MVVM创建WPF应用程序.我有一个文本框,该文本框绑定到我的ViewModel中类型为 double 的属性,默认值为0.0.如果我现在在文本框中输入文本值(例如abc),则失去焦点后,文本框将突出显示,表明值不正确.但是,用户仍然可以继续并单击提交"以调用ViewModel命令.由于文本框的 Text 属性绑定到ViewModel中 double 类型的属性,因此ViewModel属性包含默认值0.0,而我找不到用户输入的文本.

I'm creating a WPF application using MVVM. I have a textbox, which is bound to a property in my ViewModel of type double with a default value of 0.0. If I now enter a text value (say, abc) in the textbox, upon losing focus, the textbox is highlighted indicating an incorrect value. However, the user can still go ahead and click on Submit to invoke a ViewModel command. As the Text property of the textbox is bound to a property of type double in the ViewModel, the ViewModel property contains the default value, 0.0, and I'm unable to find out the text entered by the user.

因此,我无法确定用户实际上输入的值为0还是输入错误.如何正确执行此验证?我是否应该将其绑定到 string 属性,以便获取输入的文本,然后尝试将其解析为 double 值,以查看输入是否正确?还是有更好的方法呢?

Therefore, I'm unable to figure out if the user has actually entered a value of 0 or if there has been an incorrect input. How can I perform this validation correctly? Should I bind it to a string property so that I can get the entered text, and try to parse it to a double value to see if the input is correct? Or is there a better way of doing this?

<TextBox HorizontalAlignment="Left" Height="23" TextWrapping="Wrap" Text="{Binding DoubleProperty}" VerticalAlignment="Top" Width="120"/>

推荐答案

您可以将验证规则附加到文本框的绑定中,以检查该值是否为有效的double.除非输入有效值,否则这将阻止用户按下提交"按钮,从而消除了您在提交时检查DoubleProperty值是否有效的需要,因为只有启用了提交按钮后,该属性才有效.这是一个简单的示例:

You can attach a Validation Rule to the binding of the textbox that checks if the value is a valid double. This will prevent the user from being able to press the Submit button unless a valid value is entered thereby eliminating your need to check if the DoubleProperty value is valid or not upon submit because it will only be valid when the submit button is enabled. Here is a simple example:

<TextBox HorizontalAlignment="Left" Height="23" TextWrapping="Wrap" VerticalAlignment="Top" Width="120">
        <TextBox.Text>
            <Binding Path="DoubleProperty">
                <Binding.ValidationRules>
                    <validationrules:NumberValidationRule/>
                </Binding.ValidationRules>
            </Binding>
        </TextBox.Text>
    </TextBox>

在上面的示例中,您需要定义一个继承ValidationRule的NumberValidationRule类.

In the above example you need to define a class NumberValidationRule that inherits ValidationRule.

这是一个示例NumberValidationRule

Here is a sample NumberValidationRule

public class NumberValidationRule : ValidationRule
{
    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
    {
        double result = 0.0;
        bool canConvert = double.TryParse(value as string, out result);
        return new ValidationResult(canConvert, "Not a valid double");
    }
}

添加验证规则后,如果ValidationRule类指出其无效值,则文本框将在文本字段上引发错误.

Once you add a validation rule the text box will raise an error on the text field if your ValidationRule class says its not a valid value.

要阻止启用提交按钮,您可以向其添加CanExecute事件,以检查wpf窗口是否有效.像这样:

To prevent the submit button from being enabled you can add a CanExecute event to it that checks if the wpf window is valid. Like so:

<Window.CommandBindings>
    <CommandBinding Command="ApplicationCommands.Save" CanExecute="Save_CanExecute" Executed="Save_Executed"/>
</Window.CommandBindings>

... The rest of your page

<Button Content="Save" HorizontalAlignment="Left" Margin="43,146,0,0" VerticalAlignment="Top" Width="75" Command="ApplicationCommands.Save"/>                            

以及后面的代码

private void Save_CanExecute(object sender, CanExecuteRoutedEventArgs e)
    {
        e.CanExecute = IsValid(sender as DependencyObject);
    }

private bool IsValid(DependencyObject obj)
    {            
        return !Validation.GetHasError(obj) && LogicalTreeHelper.GetChildren(obj).OfType<DependencyObject>().All(IsValid);
    }

这是一个更详细的示例:

Here is a more detailed example:

在WPF中进行验证

这篇关于WPF MVVM文本框验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆