Introduction
This blog introduce how to change the background color of ComboBox Control in
WPF, When its itm selected from items list.
To changed the background color of Combobox I have declared a class name mycolor
that has two properties(Name and Color), the color property contains solid color
of brush and declared a list(MyColors) in the view modelwhose datatype is
mycolor.
I have binded the list(MyColors) with combobox, Again a property named
ComboBoxBackColor declared to binded it with background property of ComboBox. In
the SelectionChanged Command of ComboBox I am changing the background color of
Combobox.
See the Bellow code fore more clarification:
XAML CODE
<window x:class="PrintingRichTextBoxContent.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
title="MainWindow" height="755" width="702" initialized="Window_Initialized_1">
<Grid HorizontalAlignment="Left" Height="725" VerticalAlignment="Top" Width="694">
<ComboBox HorizontalAlignment="Left" x:Name="cmbColor" Margin="11,695,0,0" VerticalAlignment="Top" Width="216" ItemsSource="{Binding MyColors}" DisplayMemberPath="Name" SelectedValuePath="Color" Background="{Binding Path=ComboBoxBackColor, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
<i:Interaction.Triggers> <i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding ColorChangeCommand}" CommandParameter="{Binding ElementName=cmbColor, Path=SelectedItem}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</ComboBox>
</Grid>
</window>
View Model Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Practices.Prism.Commands;
using System.Windows.Controls;
using System.ComponentModel;
using System.Printing;
using System.Windows.Documents;
using System.Windows.Media;
namespace PrintingRichTextBoxContent
{
public class MainWindowViewModel : INotifyPropertyChanged
{
public DelegateCommand<object> ColorChangeCommand { get; set; }
public List<MyColors> MyColors { get; set; }
public Brush _ComboBoxBackColor;
public Brush ComboBoxBackColor
{
Join the conversation! Your thoughts help the community grow.