Question

Silverlight validation using INotifyDataErrorInfo was working great with its slick error displays until I started trying to use it on TextBoxes that are bound to properties of non-string data-types. My plan was to use the setters of the properties to do the validation logic, adding and removing errors from there as necessary. It works great on TextBoxes that are strings, but if you have a TextBox bound to an Int and you enter a string, the setter doesn't even get called (where I would be able to add an error that obviously non-numeric values are invalid). What is the suggested course of action from here? I've looked into ValueConverters, but they are too-far separated from the INotifyDataErrorInfo logic in my class that is being validated.

hypothetical example:

public class MyClass
{
    private string _prod;
    public string Prod
    {
        get { return _prod; }
        set //This works great
        {
            if (value.Length > 15)
            {
                AddError("Prod", "Cannot exceed 15 characters", false);
            }
            else if (value != _prod)
            {
                RemoveError("Prod", "Cannot exceed 15 characters");
                _prod= value;
            }
        }
    }

    private int _quantity;
    public int Quantity
    {
        get { return _quantity; }
        set //if a string was entered into the textbox, this setter is not called.
        {
            int test;
            if (!int.TryParse(value, test))
            {
                AddError("Quantity", "Must be numeric", false);
            }
            else if (test != _quantity)
            {
                RemoveError("Quantity", "Must be numeric");
                _quantity= test;
            }
        }
    }

    protected Dictionary<String, List<String>> errors = 
        new Dictionary<string, List<string>>();

    public void AddError(string propertyName, string error, bool isWarning)
    {
        //adds error to errors
    }
    public void RemoveError(string propertyName, string error)
    {
        //removes error from errors
    }

    //INotifyDataErrorInfo members...
}
Was it helpful?

Solution

I suggest you bind the value of the TextBox to a string value anyway and do the validation there. In case of a successful validation pass the value on to another property with the data type you are actually looking for (e.g. int). In any other case, fail the validation. Just a Workaround ... but works for me.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top