WPF数据绑定异常处理 [英] WPF Data Binding exception handling

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

问题描述

我有一个绑定到一个Integer属性的文本框。当用户输入的东西不能被转换为整数(如名称)的异常将被抛出原有的属性值不会改变文本框。我想捕捉异常,这样我可以禁用连接到该属性的命令?我该怎么办,一般来说,如果有可能从那里属性定义的视图模式?

I have a textbox that is bound to an Integer property. when the user enters something in the textbox that can't be converted to an integer (eg. name) an exception will be thrown and the original property value won't change. i want to catch the exception so that i can disable a command that is connected to that property ? how can i do that in general and if possible from the view model where the property is defined ?

推荐答案

考虑从调用视图模型,而不是从视图命令。

Consider calling the command from the view model instead of from the view.

private int _myProperty;
public int MyProperty
{
    get
    {
        return _myProperty;
    }
    set
    {
        _myProperty = value;
        // See if the value can be parsed to an int.
        int potentialInt;
        if(int.TryParse(_myProperty, out potentialInt))
        {
            // If it can, execute your command with any needed parameters.
            yourCommand.Execute(_possibleParameter)
        }
    }
}

这将允许您处理用户输入的东西不能被解析为整数, 而你只会触发命令时是什么用户输入是一个整数。

This will allow you to handle the user typing things that cannot be parsed to an integer, and you will only fire the command when what the user typed is an integer.

(我没有测试code,但我认为这可能是有益的。)

(I didn't test this code, but I think it might be helpful.)

这篇关于WPF数据绑定异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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