Combobox ItemTemplate and foreground

2019-07-06 00:00发布

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 searching for IsActive or is that binding incorrect as well?

1条回答
够拽才男人
2楼-- · 2019-07-06 00:45

The DataContext for each ComboBoxItem is a string so

  • For the TextBlock, bind to the DataContext like Text="{Binding}
  • For the DataTrigger to be able to find IsActive, use RelativeSource 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>
    
查看更多
登录 后发表回答