Binding R G B properties of color in wpf

前端 未结 1 685
故里飘歌
故里飘歌 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.

    <Window x:Class="WpfApplication16.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:my="clr-namespace:WpfApplication16"
        Title="Window1" Height="300" Width="300">
        <Window.Resources>
            <my:RgbConverter x:Key="RgbConverter" />
        </Window.Resources>
        <Window.Background>
            <SolidColorBrush>
                <SolidColorBrush.Color>
                    <MultiBinding Converter="{StaticResource RgbConverter}">
                        <Binding Path="Value" ElementName="redSlider" />
                        <Binding Path="Value" ElementName="greenSlider" />
                        <Binding Path="Value" ElementName="blueSlider" />
                    </MultiBinding>
                </SolidColorBrush.Color>
            </SolidColorBrush>
        </Window.Background>
        <StackPanel>
            <Slider Minimum="0" Maximum="255" x:Name="redSlider" />
            <Slider Minimum="0" Maximum="255" x:Name="greenSlider" />
            <Slider Minimum="0" Maximum="255" x:Name="blueSlider" />
        </StackPanel>
    </Window>
    

    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)
提交回复
热议问题