简体   繁体   中英

Visual Studio WPF XAML How to add different styles to multiple ComboBoxes?

I have 2 ComboBoxes, I need to make one white and one black.

I Right Click ComboBox > Edit Template > Edit A Copy .

There seems to be no difference in Creating a New Name or Apply to All, since it always Applies to All. The LinearGradientBrush code in the Main Template always overrides the Style in all ComboBoxes. They all end up the same color.

<LinearGradientBrush x:Key="ComboBox.Static.Background" EndPoint="0,1" StartPoint="0,0">
    <GradientStop Color="#FFF0F0F0" Offset="0.0"/>
    <GradientStop Color="#FFE5E5E5" Offset="1.0"/>
</LinearGradientBrush>

I Right Click ComboBox > Edit Template > Create Empty .

The Template is blank. I copy from the Microsoft ComboBox Template Example code, and it gives back errors.

<ControlTemplate x:Key="ComboBoxControlTemplateDark" TargetType="{x:Type ComboBox}">
    <Grid/>
</ControlTemplate>

如果要更改背景颜色,请使用组合框的Background Color属性。

If you want to add custom styles for different Comboboxes then define the style in Resource Dictinory file

add new file of type in project then add the following code

<Style x:Key="ComboboxRedStyle" TargetType="{x:Type ComboBox}">
    <Style.Triggers>
        <DataTrigger  Value="True">
              <Setter Property="BackGround" value="Red"/>
        </DataTrigger>
    </Style.Triggers>
</Style>



<Style x:Key="ComboboxBlackStyle" TargetType="{x:Type ComboBox}">
    <Style.Triggers>
        <DataTrigger  Value="True">
               <Setter Property="BackGround" value="Black"/>
        </DataTrigger>
    </Style.Triggers>
</Style>

Add the following code in app.xaml

<Application.Resources>
    <ResourceDictionary>
          <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/projectName;component/Resources/DesignResourceDictionary.xaml"/>
            <ResourceDictionary Source="/projectName;component/Resources/FocuseSettingResource.xaml"/>

        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

after including the code you can call the style for combobox where you need like below code

<ComboBox Style="{StaticResource ComboboxRedStyle}"Margin="251,38,0,0"  VerticalAlignment="Top" Width="250"   FontWeight="Bold"/>

                  <ComboBox Style="{StaticResource ComboboxBlackStyle}"Margin="251,38,0,0"  VerticalAlignment="Top" Width="250"   FontWeight="Bold"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM