WPF ComboBoxItem Background change when ComboBox SelectedIndex is -1
I'm trying to set the background color of a WPF ComboBox when the SelectedIndex is -1 in XAML. I attempted to set the background color in a trigger but I get an error telling me I can't set a binding in a property of a trigger.
thanks
<ComboBox x:Name="cbFormNameList" ItemsSource="{Binding}" DisplayMemberPath="Name" SelectedValuePath="Name"> <ComboBox.Style> <Style TargetType="{x:Type ComboBoxItem}"> <Style.Triggers> <Trigger Property="{Binding RelativeSource={Re开发者_StackOverflow社区lativeSource TemplatedParent}, Path=SelectedIndex}" Value="-1"> <Setter Property="Background" Value="#FFFAFFA9"/> </Trigger> </Style.Triggers> </Style> </ComboBox.Style> </ComboBox>
Your style is targetted at a ComboBoxItem rather than the combobox itself. The below will change the background of the ComboBox when nothing is selected:
<ComboBox.Style>
<Style TargetType="{x:Type ComboBox}">
<Style.Triggers>
<Trigger Property="SelectedIndex" Value="-1">
<Setter Property="Background" Value="#FFFAFFA9"/>
</Trigger>
</Style.Triggers>
</Style>
</ComboBox.Style>
The style should target the ComboBox directly.
Your TargetType and Trigger property are wrong. Try the following, it does work. The combobox will start out yellow and changes when you change the selection.
<ComboBox>
<ComboBoxItem>
Test
</ComboBoxItem>
<ComboBox.Style>
<Style TargetType="ComboBox">
<Style.Triggers>
<Trigger Property="SelectedIndex" Value="-1">
<Setter Property="Background" Value="#FFFAFFA9"/>
</Trigger>
</Style.Triggers>
</Style>
</ComboBox.Style>
</ComboBox>
精彩评论