views:

184

answers:

2

Hey guys! Here is the deal...

I have a ComboBox defined in my window. The content of this comboBox, is only a string list with all values in Brushes class. Nothing special so far...

But what I'm trying to achieve is a way to change the combobox background color when the user changes the color. The color would be the value selected in the list.

I'm reading about triggers and setter, but I still don't know how can I do that.

(By the way, I already have a Converter that transform a string in a valid Brush.)

<ComboBox Name="cmbColor" >
    <ComboBox.Triggers >
        <Trigger Property="SelectedIndex" > // <- Pseudocode!
            <Setter Property = "Foreground" Value="select_value_in_combo,Converter={StaticResource ColorConverter}"/>
        </Trigger>
    </ComboBox.Triggers>
</ComboBox>

Ideas?

Thanks!

+1  A: 

You don't need to use triggers for this - you can use a Binding...

bind the background colour to be the SelectedValue of the combobox - remember that you will need to convert the string to a Brush (using a class that implement IValueConverter)

will update with code sample when I get to Visual Studio...

see dabblernl's answer for the code sample :)

IanR
+2  A: 

You can solve this simply using Data binding:

<Window x:Class="ComboBoxBackgroundSpike.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:ComboBoxBackgroundSpike"
    Title="Window1" Height="300" Width="300">
    <Grid>
        <Grid.Resources>
            <local:StringToBrushConverter x:Key="StringToBrush"/>
        </Grid.Resources>
        <ComboBox Background="{Binding RelativeSource={RelativeSource Self},
                               Path=SelectedValue,
                               Converter={StaticResource StringToBrush}}"
                  ItemsSource="{Binding}">
        </ComboBox>
    </Grid>
</Window>
Dabblernl
yes - that's what I was trying to say (struggled without my IDE in front of me!!)
IanR
Dabblernl, IanR you guys are great! I was missing the "RelativeSource={RelativeSource Self}, Path=SelectedValue" part in the Binding and I didn't realized that I could also bind the background! Amazing! Thanks once again!
Rafa Borges