1

I have a ComboBox, bound to a list of objects. I can get the objects to fill the drop down just fine. I am trying to set the background color for each object in the items list of the dropdown. I can set any color for all of them easily in the below style code.

What I want to do is Bind the Background Color Value to the KeyColorValue field of my Key object.

Here is my XAML:

              DisplayMemberPath="Name" 
              HorizontalAlignment="Left" 
              Margin="300,103,0,0" 
              VerticalAlignment="Top"
              Width="186" 
              SelectionChanged="roleBoundSelector_SelectionChanged" >
        <ComboBox.ItemContainerStyle>
            <Style TargetType="ComboBoxItem">
                <Setter Property="Background"
                Value = "{Binding Path=KeyColorValue}" />    

(If I put a color in here it works just fine...need to bind to the KeyColorValue of the MyKeys Object.)

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

1 Answers1

1

Try this inside your style:

<Setter Property="Background">
    <Setter.Value>
        <Binding RelativeSource="{RelativeSource Self}" Path="DataContext.KeyColorValue"/>
    </Setter.Value>
</Setter>

The DataContext of each ComboBoxItem is an object contained in the List that is feeding the ItemsSource of the ComboBox.

Let me know if this was of any help, regards!

Hannish
  • 1,482
  • 1
  • 21
  • 33
  • This helps a great deal - I just discovered additionally that I have two choices for the data type of the color returned from the object list: One is of type System.Drawing.Color the other is a string with the Hex value of the color. Is there a way to cast or convert the type in these styles? Thank you!! – Raymond Schenk Jan 02 '13 at 21:13
  • Glad to be of help. If you think that the answer is satisfying please mark it as answer (it will raise your reputation also). Regarding the conversion, I like the second answer here http://stackoverflow.com/questions/3309709/how-do-i-convert-a-color-to-a-brush-in-xaml There are many ways to convert, but I think you'll get going with that link. Regards! – Hannish Jan 03 '13 at 00:04