2016-04-09 5 views
1

Я схожу с ума, что я просто не могу изменить цвет ComboBox. Попробовали использовать свойство фона прямо на ComboBox, но ничего не происходит.Изменение цвета фона для ComboBox, это не изменение цвета вообще

Вы также попытались использовать блок стиля и установить цвет фона, но это также не работает.

Код

<ComboBox Padding="7" Height="34" Background="#ffffff"> 
      <ComboBox.Resources> 
       <Style x:Key="{x:Type ComboBox}" TargetType="ComboBox"> 
        <Setter Property="Background" Value="red" /> 
        <Setter Property="BorderThickness" Value="1" /> 
        <Setter Property="BorderBrush" Value="black" /> 
       </Style> 
      </ComboBox.Resources> 
      <ComboBoxItem IsSelected="True">1 - Room</ComboBoxItem> 
      <ComboBoxItem>2 - Rooms</ComboBoxItem> 
      <ComboBoxItem>3 - Rooms</ComboBoxItem> 
      <ComboBoxItem>4 - Rooms</ComboBoxItem> 
      <ComboBoxItem>5+ - Rooms</ComboBoxItem> 
     </ComboBox> 

Несмотря на то, что я поставил цвет фона на белый, он по-прежнему только стандартный серый цвет.

Здесь вы можете увидеть, как это выглядит:

enter image description here

Надежда кто-то может сказать мне, что я делаю неправильно?

+0

Проверьте это [ответ] (http://stackoverflow.com/questions/22695145/wpf-change-background-color-of-a-combobox). Похоже, вам придется реализовать свой собственный ControlTemplate. –

ответ

1

вот несколько вещь, на мой взгляд, может помочь вам:

  1. Удалить определение фона из декларации ComboBox (Background = "# FFFFFF").
  2. Переместить объявление комбинированных элементов в комбинированную сетку из-за того, что ItemTemplate и ItemTemplateSelector игнорируются для элементов, уже находящихся в контейнере ItemsControl.
  3. Внедрите селектор шаблонов данных для поддержки шаблонов данных комбо (один для выбранного элемента, второй для элементов для выбора).

Вот код XAML

<Grid> 
    <Grid.Resources> 
     <x:Array Type="{x:Type system:String}" x:Key="MyRoomsArray"> 
      <system:String>1 - Room</system:String> 
      <system:String>2 - Rooms</system:String> 
      <system:String>3 - Rooms</system:String> 
      <system:String>4 - Rooms</system:String> 
      <system:String>5+ - Rooms</system:String> 
     </x:Array> 
    </Grid.Resources> 
    <ComboBox Padding="7" Height="34" SelectedIndex="0" ItemsSource="{StaticResource MyRoomsArray}"> 
     <ComboBox.Resources> 
      <DataTemplate x:Key="ItemToSelect"> 
       <Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch"> 
        <Border HorizontalAlignment="Stretch" VerticalAlignment="Stretch" 
          Background="Red" 
          BorderBrush="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ComboBox}, Path=BorderBrush, UpdateSourceTrigger=PropertyChanged}" 
          BorderThickness ="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ComboBox}, Path=BorderThickness, UpdateSourceTrigger=PropertyChanged}"> 
         <TextBlock HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Text="{Binding }" /> 
        </Border> 
       </Grid> 
      </DataTemplate> 
      <DataTemplate x:Key="SelectedItem"> 
       <Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch"> 
        <Border HorizontalAlignment="Stretch" VerticalAlignment="Stretch" 
          Background="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ComboBox}, Path=Background, UpdateSourceTrigger=PropertyChanged}" 
          BorderBrush="Transparent" 
          BorderThickness ="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ComboBox}, Path=BorderThickness, UpdateSourceTrigger=PropertyChanged}"> 
         <TextBlock HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Text="{Binding }" /> 
        </Border> 
       </Grid> 
      </DataTemplate> 
      <wpfComboBAckground:ComboDataTemplateSelector x:Key="ComboDataTemplateSelector" Selected="{StaticResource SelectedItem}" ItemToSelect="{StaticResource ItemToSelect}"/> 
      <Style TargetType="ComboBox"> 
       <Setter Property="HorizontalContentAlignment" Value="Stretch"/> 
       <Setter Property="VerticalContentAlignment" Value="Stretch"/> 
       <Setter Property="Background" Value="Red" /> 
       <Setter Property="BorderThickness" Value="1" /> 
       <Setter Property="BorderBrush" Value="Black" /> 
       <Setter Property="ItemTemplateSelector" Value="{StaticResource ComboDataTemplateSelector}"/> 
       <Style.Triggers> 
        <Trigger Property="IsMouseOver" Value="True"> 
         <Setter Property="Background" Value="Transparent"></Setter> 
        </Trigger> 
        <Trigger Property="IsMouseOver" Value="False"> 
         <Setter Property="Background" Value="Red"></Setter> 
        </Trigger> 
       </Style.Triggers> 
      </Style> 
     </ComboBox.Resources> 
    </ComboBox> 
</Grid> 

Здесь селектор шаблона данных

public class ComboDataTemplateSelector : DataTemplateSelector 
{ 
    public override DataTemplate SelectTemplate(object item, DependencyObject container) 
    { 
     var selected = false; 
     // container is the ContentPresenter 
     FrameworkElement fe = container as FrameworkElement; 
     if (fe == null) return ItemToSelect; 
     var cbo = fe.TemplatedParent as ComboBox; 

     if (cbo != null) 
      selected = true; 

     return selected ? Selected : ItemToSelect; 
    } 

    public DataTemplate Selected { get; set; } 

    public DataTemplate ItemToSelect { get; set; } 
} 

Как это выглядит: here

С уважением.

Смежные вопросы