【问题标题】:How do I retain the colors of my WPF ComboBox when I select an item?选择项目时如何保留 WPF ComboBox 的颜色?
【发布时间】:2016-01-28 22:52:53
【问题描述】:

我有一个来自在线示例的 WPF 组合框。 . .

<!-- Combo Box for specifying current projector-->
<ComboBox Height="32" HorizontalAlignment="Left" Margin="20,660,0,0" FontSize="12" FontWeight="Bold" 
          Name="comboBoxProj" Text="Projector" VerticalAlignment="Top" Width="156" SelectionChanged="comboBoxVersion_SelectionChanged">
    <ComboBoxItem Name="Proj1" Foreground="Orange">Proj1</ComboBoxItem>
    <ComboBoxItem Name="Proj2" Foreground="Red">Proj2</ComboBoxItem>
    <ComboBoxItem Name="Proj3" Foreground="Green">Proj3</ComboBoxItem>
    <ComboBoxItem Name="Proj4" Foreground="Blue">Proj4</ComboBoxItem>
    <ComboBoxItem Name="Proj5" Foreground="Cyan">Proj5</ComboBoxItem>
    <ComboBoxItem Name="Proj6" Foreground="Magenta">Proj6</ComboBoxItem>
    <ComboBoxItem Name="Proj7" Foreground="Purple">Proj7</ComboBoxItem>
    <ComboBoxItem Name="Proj8" Foreground="Yellow">Proj8</ComboBoxItem>
</ComboBox>

下拉列表以不同的颜色显示每个项目。当我从下拉列表中选择一个项目时,文本正确显示为折叠组合框的值,但只是黑色字母。从下拉菜单中以原始颜色显示文本的最简单方法是什么?

【问题讨论】:

    标签: wpf combobox


    【解决方案1】:

    你可以这样修改:

    <ComboBox Height="32" HorizontalAlignment="Left" Margin="20,660,0,0" FontSize="12" FontWeight="Bold" 
              Name="comboBoxProj" Text="Projector" VerticalAlignment="Top" Width="156" SelectionChanged="comboBoxVersion_SelectionChanged" TextElement.Foreground="{Binding RelativeSource={RelativeSource Self}, Path=SelectedValue.Foreground}">
        <ComboBoxItem Name="Proj1" Foreground="Orange">Proj1</ComboBoxItem>
        <ComboBoxItem Name="Proj2" Foreground="Red">Proj2</ComboBoxItem>
        <ComboBoxItem Name="Proj3" Foreground="Green">Proj3</ComboBoxItem>
        <ComboBoxItem Name="Proj4" Foreground="Blue">Proj4</ComboBoxItem>
        <ComboBoxItem Name="Proj5" Foreground="Cyan">Proj5</ComboBoxItem>
        <ComboBoxItem Name="Proj6" Foreground="Magenta">Proj6</ComboBoxItem>
        <ComboBoxItem Name="Proj7" Foreground="Purple">Proj7</ComboBoxItem>
        <ComboBoxItem Name="Proj8" Foreground="Yellow">Proj8</ComboBoxItem>
    </ComboBox>
    

    【讨论】:

      【解决方案2】:

      您可以在 SelectionChanged 事件处理程序中设置 Foreground 属性:

      private void comboBoxVersion_SelectionChanged(object sender, SelectionChangedEventArgs e)
      {
          ((ComboBox)sender).Foreground = ((ComboBoxItem)e.AddedItems[0]).Foreground;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-01-17
        • 1970-01-01
        • 1970-01-01
        • 2020-10-30
        • 2018-07-20
        • 2014-07-02
        • 1970-01-01
        相关资源
        最近更新 更多