在Web开发中,样式表非常常用。我记得在Swing中,有用于处理GUI的布局管理器。我是否认为XAML应用了这些范例之一?都?在这种情况下哪一个是首选。
我已经检查过intellisense但接受了Style
字段,我没有发现任何特别明显的内容,我不清楚google的关键字是什么。建议?
答案 0 :(得分:10)
您正在寻找的是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:
<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>
答案 1 :(得分:8)
更好的方式将样式存储为程序集中的资源,以便它可以作为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>