3

我正在根据 ListBox 中的 SelectedIndex >= 0 设置控件的 IsEnabled 属性。我可以在后面的代码中做到这一点,但我想为这种行为创建一个值转换器,因为这是我经常做的事情。

我创建了这个值转换器来处理任务并将其绑定到 IsEnabled 属性:

    [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
}

转换器仅在加载应用程序时调用一次。当 SelectedIndex 更改时,它不会触发。

因此,我的问题是什么导致值转换器触发?我认为这是绑定数据发生变化的时候,那么有没有办法强制转换器在不同的情况下触发?我什至问对了问题吗?

4

2 回答 2

4

它不会触发,因为您已将其绑定到Selector自身,而SelectedIndex不是Selector. WPF 将监视您绑定到的路径中的每个属性,并在这些属性中的任何一个发生更改时更新值。Selector没有改变,是SelectedIndex

于 2009-08-05T16:44:27.900 回答
2

我认为转换器可能是解决此问题的错误方法。更好的解决方案是使用RoutedCommand,并且该命令的CanExecuted方法会检查您的 SelectedIndex 是否大于或等于 0。

说了这么多,如果你仍然想使用你的值转换器,你应该知道当绑定源更新时转换器会触发。您可以使用 Binding 上的UpdateSourceTrigger属性更改更新的行为。默认情况下,它设置为PropertyChanged,但对于文本框,它设置为 LostFocus (只要文本框失去焦点,绑定就会更新)。

于 2009-08-05T16:31:46.800 回答