在@ebattulga的帮助下,这已经解决了。
我创建了一个包含多个模板覆盖的资源字典。 http://pastebin.com/nt3FxkM4
下载https://www.dropbox.com/s/20mpnbi27xv7nny/ComboBoxColors.zip?dl=0
的示例视觉工作室项目以下键在名称末尾添加了红色和蓝色:
我有2个ComboBoxes。我需要制作一个红色和一个蓝色。
我在下面做了一个示例项目。
更改画笔属性中的背景颜色不起作用。您需要覆盖默认模板样式LinearGradientBrush ComboBox.Static.Background,它是灰色和白色。
使用编辑模板我可以覆盖默认画笔将它们全部更改为红色。但我找不到一种方法来创建另一个Style来制作另一个Blue。
我正在尝试资源字典,但样式没有生效。
XAML 2 ComboBoxes
<Window x:Class="ComboBoxColors.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<ResourceDictionary Source="ComboBoxStylesDictionary.xaml"/>
</Window.Resources>
<Grid>
<ComboBox x:Name="ComboBoxRed" Style="{StaticResource ComboBoxRed}" HorizontalAlignment="Left" Margin="109,105,0,0" VerticalAlignment="Top" Width="120"/>
<ComboBox x:Name="ComboBoxBlue" Style="{StaticResource ComboBoxBlue}" HorizontalAlignment="Left" Margin="286,105,0,0" VerticalAlignment="Top" Width="120"/>
</Grid>
</Window>
资源字典
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<LinearGradientBrush x:Key="ComboBoxRed.Static.Background" EndPoint="0,1" StartPoint="0,0">
<GradientStop Color="Red" Offset="0.0"/>
<GradientStop Color="Red" Offset="1.0"/>
</LinearGradientBrush>
<SolidColorBrush x:Key="ComboBoxRed.Static.Border" Color="Red"/>
<Style x:Key="ComboBoxRed" TargetType="{x:Type ComboBox}">
<Setter Property="Background" Value="{StaticResource ComboBoxRed.Static.Background}"/>
<Setter Property="BorderBrush" Value="{StaticResource ComboBoxRed.Static.Border}"/>
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.WindowTextBrushKey}}"/>
</Style>
<LinearGradientBrush x:Key="ComboBoxBlue.Static.Background" EndPoint="0,1" StartPoint="0,0">
<GradientStop Color="Blue" Offset="0.0"/>
<GradientStop Color="Blue" Offset="1.0"/>
</LinearGradientBrush>
<SolidColorBrush x:Key="ComboBoxBlue.Static.Border" Color="Blue"/>
<Style x:Key="ComboBoxBlue" TargetType="{x:Type ComboBox}">
<Setter Property="Background" Value="{StaticResource ComboBoxBlue.Static.Background}"/>
<Setter Property="BorderBrush" Value="{StaticResource ComboBoxBlue.Static.Border}"/>
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.WindowTextBrushKey}}"/>
</Style>
</ResourceDictionary>
C#
我也尝试了这个,但找不到资源。
Brush ComboBoxRedStyle = (Brush)Application.Current.FindResource("ComboBoxRed");
ComboBoxRed.Background = ComboBoxRedStyle;
这没有效果。
ComboBoxRed.Background = Brushes.Red;
答案 0 :(得分:1)
您在App.xaml中声明资源
<Application.Resources>
<ResourceDictionary Source="ComboBoxStylesDictionary.xaml"/>
</Application.Resources>
或者如果您只在本地使用它,请使用此
Style ComboBoxRedStyle = (Style)this.FindResource("ComboBoxRed");
答案 1 :(得分:0)
在XAML中,像这样使用它,
<Page>
<Page.Resources>
<ResourceDictionary Source="GiveFileName"/>
</Page.Resources>
</Page>