Leandro
Leandro

Reputation: 950

Binding color in combobox from code wpf

First of all sorry about my English. I'm generating a datagrid with columns and rows dynamically. Every column I generate this way:

FrameworkElementFactory frameElementFactory =  
    new FrameworkElementFactory(typeof(ComboBox)); 
itemsSourceBinding.Source = finalList;
frameElementFactory.SetBinding(ComboBox.ItemsSourceProperty, itemsSourceBinding);

I have a property in the items of finalLsit that has the hexa code of a color. I need to set the background of an item in the combobox with some color depending of that code.

EDIT: I need to do it from code, like setting a binding to the frameElementFactory. I can't do it in the XAML because it is dynamically, maybe I have to create 3 columns and only one with this binding, so I must do it programatically.

Upvotes: 0

Views: 747

Answers (1)

nilbot
nilbot

Reputation: 345

Use DataTemplate: You design a template to display your items inside a combobox. For example you design a textlabel to display the color and docked at left of the dropdown menu. You should also have a converter ready to covert color (IValueConverter).

<DataTemplate DataType="{x:Type ComboBoxItem}">
     <DockPanel>        
          <TextBlock Background="{Binding HexaColor}" Width="30" DockPanel.Dock="Left" />
          .....
     </DockPanel>
</DataTemplate>

Or, you just set the resource to the combobox:

<ComboBox ItemsSource="{Binding finalList}">
    <ComboBox.Resources>
        <Style TargetType="{x:Type ComboBoxItem}">
            <Setter Property="Background" Value="{Binding ....}"/>
        </Style>
    </ComboBox.Resources>
</ComboBox>

Hope this helps

Upvotes: 1

Related Questions