Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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

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