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

C# 值转换器。强制WPF只调用一次,c#,wpf,valueconverter,C#,Wpf,Valueconverter,假设我有以下代码: <ContextMenu IsEnabled="{Binding Converter={StaticResource SomeConverterWithSmartLogic}}"> 所以,除了Converter,我并没有指定任何绑定信息……是否可以强制WPF只调用一次 UPD:此时我正在静态字段中存储值转换器的状态您是否尝试将绑定设置为onetime 如果您的转换器只能转换一次,您可以这样写转换器,如果这样做不会引起其他干扰,至少不需要静电场等 [Value

假设我有以下代码:

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

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


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

您是否尝试将绑定设置为onetime


如果您的转换器只能转换一次,您可以这样写转换器,如果这样做不会引起其他干扰,至少不需要静电场等

[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();
    }
}

是的,但它没有帮助编辑将为每个具有指定上下文菜单的项目调用VC,因为我的上下文菜单是DataTemplate的一部分(忘记说了)。然后每次选择更改时……在这种情况下,您必须在转换器中创建自己的“缓存”。是否有理由选择解决此问题而不是解决全局变量^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H静态字段使用的问题?我想这应该在ViewModel中完成,然后一起删除转换器;转换器在此实例中不应该是智能的,不要抛出NotImplementedException。这是为了那些没有实现的东西。如果ConvertBack的预期实现是抛出,那么它就是有效实现的。正确的异常应该是NotSupportedException。我认为有人可能会争论这个问题,因为在这种情况下,它实际上只是没有实现,毕竟转换回来也是可能的。对于本例,使用
NotSupportedException
当然可以。