简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM