Value Converter. Force WPF to call it only one time

2.3k views Asked by At

let's say I have following code :

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

So, I did not specified any binding information except Converter...Is it possible to force WPF to call it only one time?

UPD : At this moment i'm storing value converter's state in static fields

2

There are 2 answers

2
brunnerh On BEST ANSWER

If your converter should converter one time only you could write your converter to be that way if that does not cause other disturbances, at least that does not require static fields and the like e.g.

[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();
    }
}
3
Geert van Horrik On

Have you tried setting the binding to onetime?