简体   繁体   中英

WPF Data Binding exception handling

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?

I faced the same issue recently and I used behaviors to solve it (but you don't need them if you don't want, it was just for reusing some code I needed among different views). The main idea is to define some methods in the ViewModel that allow the view to notify errors in the input that the ViewModel cannot detect.

So, first define those methods in your ViewModel. For simplicity, I will only keep track of the number of errors, but you can store more info about them (like the actual error):

private int _errorCount = 0;
void AddUIValidationError()
{
   _errorCount++;
}

void RemoveUIValidationError()
{
   _errorCount--;
}

Then, in your View, you register for System.Windows.Controls.Validation.ErrorEvent , which is a routed event that lets you know when a component (previously configured to notify data errors) detects errors (like an exception validation error):

public partial class MyView : UserControl // or whatever it is
{
    public MyView(MyViewModel viewModel)
    {
        // Possibly ensure that viewModel is not null
        InitializeComponent();
        _myViewModel = viewModel;

        this.AddHandler(System.Windows.Controls.Validation.ErrorEvent, new RoutedEventHandler(OnValidationRaised));
    }

    private MyViewModel _myViewModel;

    private void OnValidationRaised(object sender, RoutedEventArgs e)
    {
        var args = (System.Windows.Controls.ValidationErrorEventArgs)e;

        if (_myViewModel != null)
        {

            // Check if the error was caused by an exception
            if (args.Error.RuleInError is ExceptionValidationRule)
            {
                // Add or remove the error from the ViewModel
                if (args.Action == ValidationErrorEventAction.Added)
                    _myViewModel.AddUIValidationError();
                else if (args.Action == ValidationErrorEventAction.Removed)
                    _myViewModel.RemoveUIValidationError();
            }
        }
    }
}

In the CanExecute method of your Command, you would check if the _errorCount field of your ViewModel is more than 0, and in that case, the command should be disabled.

Please note that you should must add ValidatesOnExceptions=True, NotifyOnValidationError=True to your bindings so this can work. Ex:

<TextBox Text="{Binding Path=MyProperty, ValidatesOnExceptions=True, NotifyOnValidationError=True}" />

EDIT:

Another approach, apart from what Riley mentioned (which is also good, but requires that you map each integer property from your model to a new string property in your ViewModel) is using ValidationRules. You can add ValidationRule s that are checked before parsing and calling the property setter. So you could, for example, inherit from ValidationRule and implement the Validate method to ensure that the string can be parsed to an integer. Example:

public class IntegerValidationRule : ValidationRule
{
    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        int number;
        if(Int32.TryParse((string)value, out number) == false)
            return new ValidationResult(false, "It is not a valid number");
        return new ValidationResult(true, null);
    }
}

And then, in your view define the namespace where IntegerValidationRule is defined:

<UserControl 
...
    xmlns:rules="clr-namespace:MyApplication.ValidationRules"
...>

And use the rule in your bindings:

<TextBox>
    <TextBox.Text>
       <Binding Path="MyProperty">
           <Binding.ValidationRules>

              <rules:IntegerValidationRule/>
           </Binding.ValidationRules>
       </Binding>
    </TextBox.Text>
</TextBox>

But anyway, you'll need to create classes for each non-string type you want to validate, and I think the Binding syntax now looks a bit long.

Greetings

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.)

The "best" solution I've found in the web is explained at http://www.wpfsharp.com/2012/02/03/how-to-disable-a-button-on-textbox-validationerrors-in-wpf/

In short, the Validation errors are dealt with in the View, not in the ViewModel. You do not need your own ValidationRule. Just add a style to your button in XAML:

<Button.Style>
            <Style TargetType="{x:Type Button}">
                <Setter Property="IsEnabled" Value="false" />
                <Style.Triggers>
                    <MultiDataTrigger>
                        <MultiDataTrigger.Conditions>
                            <Condition Binding="{Binding ElementName=TextBox1, Path=(Validation.HasError)}" Value="false" />
                            <Condition Binding="{Binding ElementName=TextBox2, Path=(Validation.HasError)}" Value="false" />
                        <Setter Property="IsEnabled" Value="true" />
                    </MultiDataTrigger>
                </Style.Triggers>
            </Style>
        </Button.Style>

Hope this helps someone who stumbles upon this question (I am aware that it won't likely help the OP so many years later).

We can even directly try avoiding the user from entering any char to the text box

<TextBox Name="txtBox" PreviewTextInput="NumberValidationTextBox"/>

In xaml.cs

private void NumberValidationTextBox(object sender, TextCompositionEventArgs e)
{
        e.Handled = Regex.IsMatch(e.Text, "[^0-9]+");
}

We can have check in the Model for this property which checks the value before setting it to avoid any null or empty values

private int _number;
public int Number
{
     get => _number;
     set
     {
        if(!string.IsNullOrEmpty(value.ToString())
            _number = value;
     }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM