【发布时间】:2015-09-11 12:43:10
【问题描述】:
我在这里搜索了 SO,找不到明确的答案来解释如何设置“样式资源”。在我的情况下,我的对话框控制几个按钮和列表,以及我想为其设置通用主题/样式的其他各种控件。类似于在 HTML 中使用 CSS 文件的方式。
为了在这个例子中简单起见,我想在我的所有按钮上全面使用一种样式。但是,我不希望在我的 UI 布局的 xaml 中包含所有这些样式资源。我想将样式移动到只包含样式的通用 xaml 资源文件中,这样我也可以轻松地将它们引用到整个工具中的其他 wpf 对话框中。
如何设置它以使用包含工具中各种控件样式的通用资源文件?然后能够在我的 xaml UI 中引用和使用该样式。 p>
谢谢
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="200" Width="200">
<Window.Resources>
<Style TargetType="Button" x:Key="CoolButton" >
<Setter Property="Margin" Value="1,2,1,2"/>
<Setter Property="Background" Value="LightBlue"/>
<Setter Property="HorizontalAlignment" Value="Left"/>
<Setter Property="FontSize" Value="12" />
<Setter Property="FontFamily" Value="Calibri" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border Background="{TemplateBinding Background}"
BorderBrush="Lavender" BorderThickness="5" CornerRadius="6,0,6,0" x:Name="bd">
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
Margin="{TemplateBinding Padding}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" RecognizesAccessKey="True" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="bd" Property="Background" Value="LightGray"/>
<Setter Property="Foreground" Value="White" />
<Setter Property="Cursor" Value="Hand" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<StackPanel>
<Button Style="{StaticResource CoolButton}" Content="Button" Margin="2" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75"/>
<Button Style="{StaticResource CoolButton}" Content="Button" Margin="2" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75"/>
<CheckBox Margin="2" Content="Great"></CheckBox>
</StackPanel>
</Window>
附带说明为什么在资源样式 xaml 中使用颜色变量不起作用?
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<!--COLORS-->
<Color x:Key="AccentColor">#CC4021</Color>
<Style TargetType="Button">
<Setter Property="Foreground" Value="{StaticResource AccentColor}"/>
</Style>
</ResourceDictionary>
【问题讨论】: