选择项目时,如何保留WPF ComboBox的颜色?

时间:2016-01-28 22:52:53

标签: wpf combobox

我有一个来自在线示例的WPF ComboBox。 。 。

<!-- 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>

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

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分:0)

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

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