Click here to Skip to main content
15,891,993 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
How do i set my mandatory textbox background color with color selected in colorpicker in WPF MVVM


ColorPicker SelectedColor property is of type System.Windows.Media.Color type and to set the background of textbox, i need to convert this to SolidBrushColor type.

can anyone plz help me on getting 'SolidColorBrush' Value from 'Color'


What I have tried:

.
Posted
Updated 28-Jun-17 21:39pm
v2

1 solution

First of all you must write a converter class e.g. ColorConverter.cs

using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Media;

namespace WpfApplication1
{
    public class ColorConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (!(value is Color)) return null;

            var color = (Color) value;

            var solidColorBrush = new SolidColorBrush(color);

            return solidColorBrush;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}


Then you must use it for the data binding of TextBox Background.

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication1"
        xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"        
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    
    <Window.Resources>
        <local:ColorConverter x:Key="ColorConverter"></local:ColorConverter>
    </Window.Resources>
    
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>
        <xctk:ColorPicker Name="ColorPicker"></xctk:ColorPicker>
        <TextBox Grid.Row="1"
                 Background="{Binding ElementName=ColorPicker, Path=SelectedColor, Converter={StaticResource ColorConverter}}"></TextBox>
    </Grid>
</Window>
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900