Resources and Styles
从下图,我们可以看到资源的应用场景(具体细节见扩展文章):
由'Normal'与'Large'改变字体尺寸大小
Defining Resources
ResourceDictionary,this class type stores reusable “pieces” of an application,Some of the most common reusable pieces are colors and brushes used to create an application’s color theme.
ResourceDictionary.Resources(资源字典类属性)
Every FrameworkElement has a Resources property-This property works like a standard dictionary object, so we can both add and retrieve values from it normally(after you retrieve a resource, you are free to do with it as you please)
StaticResource
one kind of most used extensions in wpf(另外一种标记扩展是Binding),this allows us to reference a previously defined resource by its Key value;
When we reference a resource in this fashion, WPF will start at the local scope and search broader and broader scopes until it finds a resource with the specified key(This means,When WPF needs to find a resource, it first examines the Resources of the current element. If the resource with the requested Key is not found, WPF will look at that element’s parent’s Resources. WPF will follow this pattern until it reaches the root element in the UI. If the resource).
DynamicResource
which allows the resource to change after the point of reference;
most often applies when you’re using system resources(f.e,the
scenario where the user changed the system color theme while your application was running);
If a DynamicResource was used, your application would update its colors on-the-fly(即时) whereas they would remain the same with a StaticResource(NOT RECOMMENDED BECAUSE THE PERFORMANCE);
<Application.Resources>
<Color x:Key=”lightBlueColor”>#FF145E9D</Color>
<Color x:Key=”darkBlueColor”>#FF022D51</Color>
<Color x:Key=”redColor”>#FFAA2C27</Color>
<Color x:Key=”greenColor”>#FF656A03</Color>
<Color x:Key=”brownColor”>#FF513100</Color>
</Application.Resources>
Color (hexadecimal notation)
Brush,color can't be applied directly,most WPF element properties like Background or Foreground require the use of a Brush;WPF has all sorts of brushes that we can paint with;SolidColorBrush is simple(Every time we declared something like Background=”Blue” we have been using some built-in default brushes);
<SolidColorBrush x:Key=”lightBlueBrush”
Color=”{StaticResource lightBlueColor}” />
<SolidColorBrush x:Key=”darkBlueBrush”
Color=”{StaticResource darkBlueColor}” />
<SolidColorBrush x:Key=”redBrush”
Color=”{StaticResource redColor}” />
<SolidColorBrush x:Key=”greenBrush”
Color=”{StaticResource greenColor}” />
<SolidColorBrush x:Key=”brownBrush”
Color=”{StaticResource brownColor}” />
Using Resources in the UI
(property-TextChanged)
SearchBar.xaml
<UserControl x:Class="ContactManager.UserControls.SearchBar"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<!--StaticResource lightBlueBrush is defined at the application’s resources, available for use here-->
<Border Background="{StaticResource lightBlueBrush}"
CornerRadius="6"
Margin="4"
Padding="4">
<DockPanel LastChildFill="False">
<TextBlock DockPanel.Dock="Left"
Text="Contact Manager"
FontWeight="Bold"
Foreground="White"
VerticalAlignment="Center"
FontSize="22"
FontFamily="Trebuchet" />
<TextBox x:Name="searchText"
DockPanel.Dock="Right"
Width="150"
Background="White"
TextChanged="SearchText_Changed" />
<Label DockPanel.Dock="Right"
Content="Search:"
FontWeight="Bold"
Foreground="White" />
</DockPanel>
</Border>
</UserControl>
//searchbar.xaml.cs
using System.Windows.Controls;
using ContactManager.Presenters;
namespace ContactManager.UserControls
{
public partial class SearchBar : UserControl
{
public SearchBar()
{
InitializeComponent();
}
public ApplicationPresenter Presenter
{
get { return DataContext as ApplicationPresenter; }
}
private void SearchText_Changed(object sender, TextChangedEventArgs e)
{
Presenter.Search(searchText.Text);
}
}
}
Combining Resources
(Property-MergedDictionaries,Source)
One very useful feature of resource dictionaries is the capability to merge them to create new dictionaries.
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source=”Resources\ColorsAndBrushes.xaml” />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
Defining Styles
Styles allow a way to declare common property values on any FrameworkElement(almost anything can be added to a resource dictionary, but styles are perhaps the most common items-every FrameworkElement has a Style property that we can get or set to an instance of a Style);
(1)just like CSS(cascading style sheet)
(2)must have a TargetType to declare to what it should be applied;
(3)a Setter to declare a reusable property/value pair that can be applied to the TargetType(done by setting property attribute to the name of a property on the TargetType and the Value attribute to the desired value);
Setter values can be simple or complex objects;
Both Style and Setter have several constructors that make instantiation more convenient;
(4)have no Key defined(or implicitly keyed),a Style resource is a special case because its key can be implicitly based on its TargetType value,which allows WPF to automatically apply styles to elements whose type matches the TargetType property within the given scope;
<Style TargetType=”{x:Type GroupBox}”>
<Setter Property=”Margin”
Value=”5” />
<Setter Property=”Padding”
Value=”5” />
<Setter Property=”BorderThickness”
Value=”2” />
</Style>
<Style TargetType=”{x:Type Label}”>
<Setter Property=”FontWeight”
Value=”Bold” />
<Setter Property=”FontSize”
Value=”12” />
<Setter Property=”HorizontalAlignment”
Value=”Right” />
</Style>
Using Keyed Styles
every FrameworkElement has a Style property,we can set it using the StaticResource extension.
inherit styles one from another (property-BasedOn,can be used to reference other styles and effectively enable style inheritance.only must we determine a compatible base class for all the styles involved)
<Style TargetType=”{x:Type Label}”
BasedOn=”{StaticResource baseControlStyle}”>
<Setter Property=”HorizontalAlignment”
Value=”Right” />
<Setter Property=”FontWeight”
Value=”Bold” />
</Style>
小结:
Q:What's resource?!
A:Resources are the typical home of styles but they are not limited to storing them alone. Any CLR object with a parameterless constructor can be stored inside a resource dictionary and easily accessed later by key.(As you work more with WPF, you will find that combining these features deeply enables rich, dynamic application development. )
既然是可描述编程,就不能留有盲区,Resource至少具有这样的作用,并能够完成;而且它涉及到cross-cutting concerns.
资源,在wpf中,有公共使用的类型这种含意。(In next hour,we can see,when we declare a PhoneConverter in the resources, it creates a single instance that is used for the entire application. If we were to declare the converter inline, we would be creating a new instance for each binding.正因为是公用的,所以使用Key属性为名)
Style = control or multiple controls displaying(or appearance) rules of application context
Classical Mobile phone = gesture + style
扩展:WPF中资源的由来.