WPF Data Binding exception handling

后端 未结 3 1269
眼角桃花
眼角桃花 2021-01-06 17:17

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 t

3条回答
  •  攒了一身酷
    2021-01-06 17:46

    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.

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

提交回复
热议问题