2016-01-28 2 views
0

У меня есть 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> 

Выпадающий список отображает каждый элемент другого цвета. Когда я вычеркиваю элемент из раскрывающегося списка, текст отображается правильно как значение свернутого 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> 
0

Вы можете установить Foreground свойство в обработчике события SelectionChanged:

private void comboBoxVersion_SelectionChanged(object sender, SelectionChangedEventArgs e) 
{ 
    ((ComboBox)sender).Foreground = ((ComboBoxItem)e.AddedItems[0]).Foreground; 
} 
Смежные вопросы