views:

12

answers:

0

I am using a ComboBox with IsEditable set to true filled with Employee entities. Typing a valid employee name will select that employee from the list but if a name is typed that doesn't exist in the list, there's no indication that SelectedItem is null. To get around this I have created a simple validation rule on the SelectedItem binding as follows:

class SelectionExistValidator : ValidationRule
{
    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
    {
        if (value == null)
            return new ValidationResult(false, "Item not found");

        return new ValidationResult(true, null);
    }
}

This results in a nice red box outline whenever a match is not made, but it as a side effect validation also fails when the combobox is cleared. This is undesirable, as it is acceptable to leave this field blank.

A nice way to detect this situation would be to check if I could do something like the following:

var text = combo.Text;
var selection = combo.SelectedItem;

if (selection == null && text.Length > 0)
    return new ValidationResult(false, "Item not found");

return new ValidationResult(true, null);

Unfortunately, I can't think of a way to get the value of the Text property in a validator. Is there a way to accomplish this?