Combobox ItemTemplate and foreground
I have a comboBox that is bound to a list of strings from my viewModel. What I am trying to do is have the foreground of a comboBox item be set to a different color if a property in my viewModel is true:
<ComboBox x:Name="myComboBox" ItemsSource="{Binding Names}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding ...}">
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<Style.Triggers>
<DataTrigger Binding="{Binding IsActive}" Value="True">
<Setter Property="Foreground" Value="Navy"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
I am not sure what to bind the Text of the TextBlock to. All I want is to display the list of strings. I always end up with a dropdown that has the items but they are not visible. I tried removing the style trigger thinking that maybe I was screwing up there, but that didn't help.
Am I taking the right approach? Will the ComboBox.ItemTemplate correctly look at my viewModel (which is the data context) when se开发者_StackOverflow社区arching for IsActive or is that binding incorrect as well?
The DataContext
for each ComboBoxItem
is a string so
- For the
TextBlock
, bind to theDataContext
likeText="{Binding}
For the
DataTrigger
to be able to findIsActive
, useRelativeSource
in the binding<ComboBox x:Name="myComboBox" ItemsSource="{Binding Names}"> <ComboBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding}"> <TextBlock.Style> <Style TargetType="{x:Type TextBlock}"> <Style.Triggers> <DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType={x:Type ComboBox}}, Path=DataContext.IsActive}" Value="True"> <Setter Property="Foreground" Value="Navy"/> </DataTrigger> </Style.Triggers> </Style> </TextBlock.Style> </TextBlock> </DataTemplate> </ComboBox.ItemTemplate> </ComboBox>
精彩评论