简体   繁体   English

Visual Studio WPF XAML如何将不同的样式添加到多个ComboBox?

[英]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. 我有2个ComboBox,我需要制作一个白色和一个黑色。

I Right Click ComboBox > Edit Template > Edit A Copy . 我右键单击ComboBox>编辑模板> 编辑副本

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. 主模板中的LinearGradientBrush代码始终会覆盖所有ComboBox中的Style。 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 . 我右键单击ComboBox>编辑模板> 创建空

The Template is blank. 模板为空白。 I copy from the Microsoft ComboBox Template Example code, and it gives back errors. 我从Microsoft ComboBox模板示例代码复制,并且返回错误。

<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 在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"/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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