"Traditional application resources consist of binary chunks of data, typically representing things such as icons, bitmaps, strings, and XML. In fact, the .NET framework provides
generic support for these through the ResourceManager class.
WPF is no different—binary resources play an important role in a typical application.
However, WPF goes a lot further with another kind of resource: logical resources.
These are objects, any objects, which can be shared and used in a multitude of locations
throughout the application; they can even be accessed across assemblies. Some
of WPF's features, such as implicit (automatic) styles and type-based data templates,
rely on the logical resources system."

传统的资源一般是指大块的二进制资源,典型的如图片、xml文件等,.NET提供了ResourceManager类来管理这些资源。而WPF引进了另一种形式的资源-logical resources(逻辑资源),它可以是任何需要共享的对象。WPF的许多特性也都依赖逻辑资源系统。

These objects are typically placed inside a
ResourceDictionary and located at runtime using a hierarchical search.”

下面通过一个例子,说明为什么需要logical resource、如何在XAML中及Code behind file中访问logical resource。

1.为什么需要Logical Resource?

假如我们需要为一个rectangle的Fill属性赋一个LinearGradientBrush值。通常实现如下:

        <Rectangle Height="100" Stroke="Red">
<Rectangle.Fill>
<LinearGradientBrush >
<GradientStop Offset="0.3" Color="Green"/>
<GradientStop Offset="0.8" Color="Brown"/>
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>

假如,现在我们另外还有1个Rectangle需要同样的Brush,当然我们可以Copy上面的<Rectangle.Fill>...</Rectangle.Fill>,这样可以满足需求,但是这样的Copy很让人头疼。
Logical resource能够解决这个问题。

2.定义logical resource

我们可以把上面的Brush放到Window.Resources中,如下:

    <Window.Resources>
<LinearGradientBrush x:Key="brush1">
<GradientStop Offset="0.3" Color="Green"/>
<GradientStop Offset="0.8" Color="Yellow"/>
</LinearGradientBrush>
</Window.Resources>

注意以下2点:
a.“Every element (deriving from FrameworkElement) has a Resources property of type
ResourceDictionary. This means that every element can have resources associated with
it.”

每个element都有Resources属性。

b.“The Resources property is a dictionary.In XAML, the x:Key attribute must be specified (most of the time; exceptions to this rule
will be discussed in relation to styles and data templates).”

在XAML中x:key必须声明,style和data templates有些例外(x:Type)。

3.在XAML中使用

添加完成后,我们可以在XAML中通过StaticResource(后面介绍DynamicResource)这个markup extension,很方便的使用这个logical resource

<Rectangle Height="100" Fill="{StaticResource brush1}"/>

4.在Code Behind File中使用

如为下面的Ellipse赋Fill值

<Ellipse x:Name="ellipse2" Stroke="Red" StrokeThickness="20" Height="100" />

我们有两种方法获取这个Resource。

方法a:通过FrameworkElement.FindResource ,此方法在找不到的时候放回null,因此最好加个null判断。

Brush brush1 = (Brush)ellipse2.FindResource("brush1");
if (brush1 != null)
{
ellipse2.Fill = brush1;
}

方法b.是资源可以通过它的索引直接获得。由于我们知道定义资源的是哪个element,我们可以直接使用element.Resources["name"]获得。本例定义的是Window的资源,因此是:

Brush brush = (Brush)this.Resources["brush1"];

5.Logical Resource是如何匹配的?

如上面的

<Rectangle Height="100" Fill="{StaticResource brush1}"/>

This causes a search from the current element (the Rectangle) up the element tree, looking
for a resource with the key brush1; if found, its associated object is used as the property's
value. If not found on any element up to the root Window, the search continues within the
resources of Application (typically located in the App.xaml file). If not found even there,
a runtime exception is thrown. This is depicted in the following diagram:”

附:完整的XAML和Code Behind File如下:

<Window x:Class="UsingLogicalResources.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>
<LinearGradientBrush x:Key="brush1">
<GradientStop Offset="0.3" Color="Green"/>
<GradientStop Offset="0.8" Color="Yellow"/>
</LinearGradientBrush>
</Window.Resources>
<StackPanel>
<Rectangle Height="100" Stroke="Red">
<Rectangle.Fill>
<LinearGradientBrush >
<GradientStop Offset="0.3" Color="Green"/>
<GradientStop Offset="0.8" Color="Brown"/>
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>
<Ellipse x:Name="ellipse2" Stroke="Red" StrokeThickness="20" Height="100" />
<Rectangle Height="100" Fill="{StaticResource brush1}"/>
</StackPanel>
</Window>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes; namespace UsingLogicalResources
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent(); //Brush brush1=(Brush)this.Resources["brush1"];
Brush brush1 = (Brush)ellipse2.FindResource("brush1");
if (brush1 != null)
{
ellipse2.Fill = brush1;
}
}
}
}

运行,如下:

WPF整理-使用逻辑资源的更多相关文章

  1. WPF整理-二进制资源和内容

    WPF中的Binary Resource(二进制资源)是相对于前面所说的Logical resource(逻辑资源)而说的,一般指Image.XML文件等. 注意:这里说的是Resource" ...

  2. WPF教程九:理解WPF中的对象资源

    在WPF中,所有继承自FrameworkElement的元素都包含一个Resources属性,这个属性就是我们这篇要讲的资源. 这一篇讲解的资源是不是上一篇的程序集资源(那个是在编译过程中打包到程序集 ...

  3. WPF整理-Style

    "Consistency in a user interface is an important trait; there are many facets of consistency,   ...

  4. WPF整理-XAML构建后台类对象

    1.XAML 接触WPF的第一眼就是XAML---XAML是用来描绘界面的.其实不然! "Actually, XAML has nothing to do with UI. It's mer ...

  5. 【转载】国外程序员整理的Java资源大全

    以下转载自: 推荐!国外程序员整理的Java资源大全中文版    https://github.com/akullpp/awesome-java英文版 Java 几乎是许多程序员们的入门语言,并且也是 ...

  6. WPF之神奇的资源

    原文:WPF之神奇的资源 WPF中的资源有两种,一种称为"程序集资源"(assembly resource),另一种称为"对象资源"(object resour ...

  7. WPF整理-使用用户选择主题的颜色和字体

    “Sometimes it's useful to use one of the selected colors or fonts the user has chosen in theWindows ...

  8. WPF整理-自定义一个扩展标记(custom markup extension)

    "Markup extensions are used to extend the capabilities of XAML, by providing declarativeoperati ...

  9. WPF整理-XAML访问静态属性

    "XAML provides an easy way to set values of properties—type converters and the extended propert ...

随机推荐

  1. Linux tar (打包.压缩.解压缩)命令说明 | tar如何解压文件到指定的目录?

    打包举例:将 /usr/local/src/zlib-1.2.5目录下的文件打包成 zlib-1.2.5.tar.gz cd /usr/local/src tar -czvf ./zlib-1.2.5 ...

  2. SharePreferences的DB实现

    存储一些简单数据的时候,最快的实现是用SharePreferences,但SharePreferences的可靠性不高,在某些非官方ROM上,总是存取失败.后来想到用数据库来存取.产品中,存取的数据项 ...

  3. Ubuntu远程vnc配置

    1. 安装xrdp 使用快捷键"Ctrl+Alt+T"打开一个终端窗口,输入"sudo apt-get install xrdp"-->回车-->输 ...

  4. Linux pthread

    #include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h& ...

  5. [Linux]系统调用理解(4)

    这是本专栏中进程相关的系统调用的最后一篇,用2个实例演示了以往学习的内容.其一是Mini Shell,仿常用的Bash而做,但对其作了大大简化:其二是一个Daemon程序,可以使读者一窥服务器编程的端 ...

  6. 创建 WPF 工具箱控件

    创建 WPF 工具箱控件 WPF (Windows Presentation Framework) 工具箱控件模板允许您创建 WPF 控件,会自动添加到 工具箱 安装扩展的安装. 本主题演示如何使用模 ...

  7. ACM/ICPC 之 卡卡的矩阵旅行-最小费用最大流(可做模板)(POJ3422)

    将每个点拆分成原点A与伪点B,A->B有两条单向路(邻接表实现时需要建立一条反向的空边,并保证环路费用和为0),一条残留容量为1,费用为本身的负值(便于计算最短路),另一条残留容量+∞,费用为0 ...

  8. VC++ 制作一个简易的控制台时钟应用

    1.下载EasyX Library for C++ (http://www.easyx.cn/) 直接下载:EasyX_20151015(beta) EasyX 绘图库目前支持 Visual C++ ...

  9. TFS二次开发系列:五、工作项查询

    本节将讲述如何查询工作项,用于二次开发中定义获取工作项列表. 使用WorkItemStore.Query方法进行查询工作项,其使用的语法和SQL语法类似: Select [标题] from worki ...

  10. SQL Server Database 维护计划创建完整的备份策略

    SQL Server的维护计划Maintenance Plan是一个非常实用的维护工具,可以完成大多数的数据库维护任务,通过对这些功能的封装,可以省去很多的代码编写时间.网络上完整介绍的不是很多,特此 ...