jo johny
jo johny

Reputation: 13

checkcombobox color of the background of items

I am creating application in c# and wpf. Is there a way to make checkcombobox from this namespace xctk="http://schemas.xceed.com/wpf/xaml/toolkit" with different color in every item.

enter image description here

I have ObservableCollection<Item> Items which is bind to the checkComboBox. In class Item is field: Color color, which color I want to show.

<xctk:CheckComboBox Name="CheckComboBox"  ItemsSource="{Binding Items}" FontFamily="Times New Roman" FontSize="20" Margin="190,553,254,126"   />

Upvotes: 1

Views: 629

Answers (2)

Coskun Ozogul
Coskun Ozogul

Reputation: 2487

You can do this by using ObservableCollection as items source or by adding one by one ComboboxItems into your combobox.

You can modify your comboboxitem's properties.

ComboboxItem item = new ComboboxItem();
item.Content = "Item1";
item.Tag = "Any value"; You can assign any object and use for exemple in selection change event.
item.Background = new SolidColorBrush(Colors.Red);
myCombobox.Items.Add(item);

Or

ObservableCollection<ComboboxItem> myList = new ObservableCollection<ComboboxItem>();

  ComboboxItem item = new ComboboxItem();
item.Content = "Item1";
item.Tag = "Any value"; You can assign any object and use for exemple in selection change event.
item.Background = new SolidColorBrush(Colors.Red);
myList.Add(item);

myCombobox.ItemsSource = myList;

In this case, you can use SelectedItem in order to get the value that you need :

 if(myCombobox.SelectedItem != null)
  {
   var myObject = (myCombobox.SelectedItem as ComboboxItem).Tag as MyObject; //My object can be any type.
   var idValue = myObject.ID;
  }

Upvotes: 1

Alex.Wei
Alex.Wei

Reputation: 1883

I don't know the structure of xceed's CheckComboBox, but here is an idea should work. Frist, find out the root element that response for present the each item binded to the CheckComboBox. Then write a Style in CheckComboBox.Resources target to the type of that element to override its Background property with a SolidBrush that has the color in the item through a Binding. And if necessary, override other visual related properties like Margin, HorizontalAlignment ect. If we do that with a ComboBox, it should like below

<ComboBox ItemSource="{Binding Items}">
    <ComboBox.Resources>
        <Style TargetType="ComboBoxItem">
            <Setter Property="Backgournd">
                <Setter.Value>
                    <SolidColorBrush Color="{Binding RelativeSource=
                    {RelativeSource AncestorType=ComboBoxItem},
                    Path=Content.Color}"/>
                </Setter.Value>
            </Setter>
            <Setter Property="Margin" Value="-1 -1"/>
        </Style>
    </ComboBox.Resources>
</ComboBox>

Upvotes: 0

Related Questions