Binding R G B properties of color in wpf

前端 未结 1 694
故里飘歌
故里飘歌 2020-12-30 15:27

I have a custom class, \"FavoriteColor\" that has three properties, R, G and B. Now I want to draw a rectangle and fill it

1条回答
  •  忘掉有多难
    2020-12-30 16:08

    Let's do this using a MultiBinding and an IMultiValueConverter. Here's a full sample.

    First, the xaml for Window1. We'll set up three Sliders and bind their values to the Window's Background property via a SolidColorBrush.

    
        
            
        
        
            
                
                    
                        
                        
                        
                    
                
            
        
        
            
            
            
        
    
    

    Next, the converter. Note that I'm not doing any error checking here - you really should check that the length of the values array is 3 and that the individual values are valid bytes etc.

    public class RgbConverter : IMultiValueConverter
    {
        #region IMultiValueConverter Members
    
        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            var r = System.Convert.ToByte(values[0]);
            var g = System.Convert.ToByte(values[1]);
            var b = System.Convert.ToByte(values[2]);
    
            return Color.FromRgb(r, g, b);
        }
    
        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    
        #endregion
    }
    

    That's it! No other code-behind is necessary.

    0 讨论(0)
提交回复
热议问题