2

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

illegal-immigrant
  • 8,089
  • 9
  • 51
  • 84
  • Is there a reason to choose solving this problem instead of solving the problem of global variable^H^H^H^H^H^H^H^H^H^H^H^H^H^H^Hstatic field usage? – R. Martinho Fernandes Feb 10 '11 at 12:06
  • IMHO This should just be done in a ViewModel and remove the converter all together; a converter should not be smart in this instance – Aaron McIver Feb 10 '11 at 15:09

2 Answers2

1

Have you tried setting the binding to onetime?

Geert van Horrik
  • 5,689
  • 1
  • 18
  • 32
1

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();
    }
}
H.B.
  • 166,899
  • 29
  • 327
  • 400
  • Don't throw NotImplementedException. That is for stuff that isn't implemented. If the intended implementation of ConvertBack is to throw, then it is effectively implemented. The correct exception would be NotSupportedException. – R. Martinho Fernandes Feb 10 '11 at 12:13
  • I think one could argue about that because in this case it in fact just was not implemented, after all converting back would be possible as well. For this example right here using `NotSupportedException` is fine of course. – H.B. Feb 10 '11 at 12:46