How can I convert the values of three sliders into a Color?

前端 未结 2 1310
执念已碎
执念已碎 2020-12-22 07:29

I\'m trying to create a custom user control that will allow a user to define a color in WPF. I\'ve done this before in WinForms but in WPF it seems to be not as straight for

2条回答
  •  囚心锁ツ
    2020-12-22 08:04

    First of all, I'd recommend making these changes to your ByteToColorConverter:

    public class DoubleToColorConverter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            // Values bound to sliders are going to be doubles.
            return Color.FromScRgb((float)(double)values[0], (float)(double)values[1], (float)(double)values[2], (float)(double)values[3]);
        }
    
        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
        {
            Color C = (Color)value;
            return new object[] { (double)C.ScA, (double)C.ScR, (double)C.ScG, (double)C.ScB };
        }
    }
    

    I've switched from bytes to doubles, as the slider value you're trying to bind to will only return/accept doubles. The (float)(double) cast is to deal with unboxing the values in the array.

    With this XAML, I was able to get a basic ARGB colour mixer working. Notice I've changed the Min/Max values on the slider, now we're not dealing with bytes anymore.

    
        
        
        
        
        
            
                
                    
                        
                            
                            
                            
                            
                        
                    
                
            
        
    
    

    If you wanted to bind a single slider to the converter, you could update your converter to inspect the number of values in the values[] array. You could perhaps use the ConverterParameter to pass in the colour you'd like that single slider to affect ... something like this:

    
        
    
    

提交回复
热议问题