【发布时间】:2012-11-08 08:16:43
【问题描述】:
在 Web 开发中,样式表非常常用。在 Swing 中有用于处理 GUI 的布局管理器。我是否正确假设 XAML 应用了这些范例之一?两个都?在这种情况下首选哪一个?
我检查了 Intellisense,但除了 Style 字段外,我没有发现任何特别明显的内容,而且我不清楚谷歌搜索哪些关键字。有什么建议吗?
【问题讨论】:
标签: xaml
在 Web 开发中,样式表非常常用。在 Swing 中有用于处理 GUI 的布局管理器。我是否正确假设 XAML 应用了这些范例之一?两个都?在这种情况下首选哪一个?
我检查了 Intellisense,但除了 Style 字段外,我没有发现任何特别明显的内容,而且我不清楚谷歌搜索哪些关键字。有什么建议吗?
【问题讨论】:
标签: xaml
您正在寻找的是 ResourceDictionary。这比仅仅将样式放在 App.Resources 元素中要灵活得多,并且可以让您更好地控制样式的范围。
将样式放入您的 App.Resources 有许多缺点:
使用 ResourceDictionary 在很大程度上解决了这个问题:
资源字典非常接近地映射到 CSS 文件。基本上,您使用这些来存储混合的东西:
并且,与样式表一样,您可以将它们应用于整个控件类型或使用命名样式的控件
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/Project.Ui;component/Styles/DialogStyles.xaml"/>
<ResourceDictionary Source="pack://application:,,,/Project.Ui;component/Icons/Error.xaml"/>
<ResourceDictionary Source="pack://application:,,,/Project.Ui;component/Icons/Exit.xaml"/>
<ResourceDictionary Source="pack://application:,,,/Project.Ui;component/Icons/Warning.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</UserControl.Resources>
定义资源字典:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:po="http://schemas.microsoft.com/winfx/2006/xaml/presentation/options"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:Infrastructure="clr-namespace:Hsbc.Ice.Shell.Infrastructure"
xmlns:Ui="clr-namespace:Hsbc.Ice.Shell.Infrastructure.Ui">
<LinearGradientBrush x:Key="{x:Static Ui:Brushes.SelectedRowBackgroundBrushKey}" StartPoint="0.5,0" EndPoint="0.5,1"
po:Freeze="True">
<GradientStop Color="#4D5F6E96" Offset="0"/>
<GradientStop Color="#2191A0BE" Offset="0.2"/>
<GradientStop Color="#2191A0BE" Offset="0.45"/>
<GradientStop Color="#745F6E96" Offset="1"/>
</LinearGradientBrush>
</ResourceDictionary>
【讨论】:
将样式作为资源存储在程序集中的更好方法,以便它可以在多个文件中作为 css 使用
您可以查看:Silverlight and styles
同时检查:How to set Silverlight Control Styles via Application.Resources
将这样的样式放入 Application.Xaml 文件中或为您创建一个新样式
<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="AppResStyle.App"
>
<Application.Resources>
<Style x:Key="ButtonStyle" TargetType="Button">
<Setter Property="BorderBrush" Value="Green" />
<Setter Property="Foreground" Value="Blue" />
</Style>
</Application.Resources>
</Application>
现在您可以在多个 uercontrol 中使用这样的方式为按钮分配样式
<UserControl x:Class="AppResStyle.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="130" Height="80">
<Grid x:Name="LayoutRoot" Background="White">
<Button Content="Button1" Height="75" Width="125" Style="{StaticResource ButtonStyle}" />
</Grid>
</UserControl>
【讨论】: