什么导致价值转换器触发? [英] What causes a Value Converter to fire?

查看:101
本文介绍了什么导致价值转换器触发?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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
}

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

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?

推荐答案

它不会触发,因为你已经绑定到选择器本身,而不是选择器 SelectedIndex 属性。 WPF将监视您绑定的路径中的每个属性,如果这些属性中的任何一个更改,则更新值。 选择器不会更改, SelectedIndex 是。

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.

这篇关于什么导致价值转换器触发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆