Search code examples
c#wpfxamlcolorsbrush

Color from the WPF ColorPicker to a Rectangle brush?


I have a Rectangle property and the ColorPicker from the Extended WPF Toolkit in my colorprotype.xaml

<Rectangle Name="rect_NewSelect" Grid.Row="0" Style="{DynamicResource ColorInfoRectangle}" Width="60"/>

And

<xctk:ColorPicker x:Name="ClrPcker_Background" Margin="-36,-389,2,411" RenderTransformOrigin="0.476,0.4" SelectedColor="Transparent" MouseDown="ColorPickerColor_MouseDown" DisplayColorAndName="True"   Height="20" VerticalAlignment="Bottom"/>

So I placed the "MouseDown" event in my colorprotype.xaml.cs of the ColorPicker to be able to put the selected color from the Picker in the rectangle.

private void ColorPickerColor_MouseDown(object sender, MouseButtonEventArgs e)
    {
        if (rect_NewSelect == null) return;
        rect_NewSelect.Fill = ClrPcker_Background.SelectedColor;

    }

But after putting this, an error occurs and tells me:

Unable to convert System.Windows.Media.Color type to System.Windows.Media.Brush.

So, How can I convert "Color" to "Brush"? What is the monumental error in my code?

Knowing that: my project is coded in C # with .NET 4.6.1. enter image description here

From the image: ColorPicker = Red combobox and Rectangle = Blue


Solution

  • You could handle the SelectedColorChange event of the ColorPicker like this:

    <xctk:ColorPicker x:Name="ClrPcker_Background" Margin="-36,-389,2,411"
                      RenderTransformOrigin="0.476,0.4" SelectedColor="Transparent"
                      SelectedColorChanged="ClrPcker_Background_SelectedColorChanged" DisplayColorAndName="True" 
                      Height="20" VerticalAlignment="Bottom"/>
    

    private void ClrPcker_Background_SelectedColorChanged(object sender, RoutedPropertyChangedEventArgs<Color?> e)
    {
        if (rect_NewSelect == null || ClrPcker_Background == null || !ClrPcker_Background.SelectedColor.HasValue)
            return;
    
        rect_NewSelect.Fill = new SolidColorBrush(ClrPcker_Background.SelectedColor.Value);
    }
    

    You should access the Value property of the SelectedColor property to get the actual Color object that was selected.