Search code examples
wpfxamlmathopacityivalueconverter

WPF XAML IValueConverter Math Trouble


I have a converter bound to a datagridcell's opactity as such:

<Setter Property="Opacity" Value="{Binding Number, Converter={StaticResource OpacityConverterKey}}" />

And here is my Converter:

public class OpacityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
    int val = System.Convert.ToInt32(value);
    int min = 10;
    int max = 50;

        if (val > max)
            return 0.5;
        else if (val < min)
            return 1.0;
        else
            return 1.0 - (val * 0.01);
    }
    
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }

}

The problem that I am having is creating a smooth scale that goes from opacity 0.5 to 1.0 depending on is the value of Number is between 10 and 50.

For example,

On the upper end everything is smooth:

Number:49 = opacity:0.51

Number:50 = opacity:0.50 -----> Smooth 0.01 steps

Number:51 = opacity:0.50

But, on the lower end the transition is not smooth:

Number:9 = opacity:1.0

Number:10 = opacity:0.9 -----> Note the 0.1 jump that doesn't occur on the upper end

Number:11 = opacity:0.89

I just need help with my formula to make the opacity transition smooth.

I have tried:

return 1.1 - (val * 0.01);

but then the lower end is smooth and there is a 0.1 jump on the upper end.

Thank you for your time.


Solution

  • This should work:

    public object Convert(
        object value, Type targetType, object parameter, CultureInfo culture)
    {
        int val = (int)value;
        int val1 = 10;
        int val2 = 50;
        double result1 = 1;
        double result2 = 0.5;
        double result = (val - val1) * (result2 - result1) / (val2 - val1) + result1;
        return Math.Min(Math.Max(result, result2), result1);
    }