开发者

Use ComboBoxItem text as value for a Property Setter

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!


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>


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 :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜