价值转换器。强制WPF只调用一次

时间:2011-02-10 11:49:59

标签: c# wpf valueconverter

假设我有以下代码:

<ContextMenu IsEnabled="{Binding Converter={StaticResource SomeConverterWithSmartLogic}}">

所以,除了Converter之外,我没有指定任何绑定信息......是否可以强制WPF只调用一次?

UPD:此时我将值转换器的状态存储在静态字段中

2 个答案:

答案 0 :(得分:1)

您是否尝试过将绑定设置为一次?

答案 1 :(得分:1)

如果您的转换器只应转换一次,那么如果不会引起其他干扰,您可以将转换器编写为这样,至少不需要静态字段等。

[ValueConversion(typeof(double), typeof(double))]
public class DivisionConverter : IValueConverter
{
    double? output; // Where the converted output will be stored if the converter is run.

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (output.HasValue) return output.Value; // If the converter has been called 
                                                  // 'output' will have a value which 
                                                  // then will be returned.
        else
        {
            double input = (double)value;
            double divisor = (double)parameter;
            if (divisor > 0)
            {
                output = input / divisor; // Here the output field is set for the first
                                          // and last time
                return output.Value;
            }
            else return DependencyProperty.UnsetValue;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}