views:

190

answers:

2

I am setting an IsEnabled property of a control based on whether or not a SelectedIndex >= 0 in a ListBox. I can do this in the code behind, but I wanted to create a value converter for this behavior since it is something I do frequently.

I created this Value Converter to handle the task and bound it to the IsEnabled property:

    [ValueConversion(typeof(Selector), typeof(bool))]
public class SelectorItemSelectedToBooleanConverter : IValueConverter
{
    #region IValueConverter Members
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null || !(value is Selector))
            return null;

        var control = value as Selector;
        return control.SelectedIndex >= 0;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion
}

The Converter is only called once, when the application is loaded. It does not fire when the SelectedIndex changes.

My question is therefore what causes a Value Converter to fire? I assume it is when the bound data changes, so is there a way to force the converter to fire in different circumstances? Am I even asking the right question?

+1  A: 

I think a converter might be the wrong way to go about this. A better solution would be to use a RoutedCommand, and the command's CanExecuted method checks to see if your SelectedIndex is greater than or equal to 0.

That much being said, if you still want to use your value converter, you should know that the converter fires whenever the binding source updates. You can change the behavior of the update using the UpdateSourceTrigger property on the Binding. By default this is set to PropertyChanged, but for textboxes it is set to LostFocus (whenever the textbox loses focus the binding is updated).

Charlie
+2  A: 

It won't fire because you've bound it to the Selector itself, not the SelectedIndex property of the Selector. WPF will monitor every property in the path you bind to, and update values if any of those properties changes. The Selector isn't changing, the SelectedIndex is.

HTH, Kent

Kent Boogaart
When I read ArsenMkrt's comment above I came to the same conclusion. I can change the Converter easy enough: I was thinking this would be useful for any of the Selector types, and more descriptive, but what you say makes sense.
Joel Cochran