zoukankan      html  css  js  c++  java
  • (三)资源

    • 概述

      在WPF中资源分为两类:静态资源和动态资源,分别可以使用StaticResource和DynamicResource标记进行引用.

       静态资源不会基于运行时重新求值,你可以根据需要避免大量不必要的动态资源来提高性能.

       动态资源适用于在运行时才能确定的情况.

    • 静态资源:

      静态资源的查找通过设定属性元素定义的资源字典中查找所请求的键,然后查找过程向上遍历逻辑树,直到到达父元素及其资源字典为止.此行为在到达根元素之前将一直持续.接下来会检查Application对象中定义的资源字典中的资源.
      根据这个原理,如果你使用静态资源的引用,必须合理的设计资源字典的结构.找不到资源时会发生异常.
    • 动态资源:
    动态资源的查找支持向前引用,这是由于资源在运行时才需要进行求值.所以当你有一个依存关系的复杂资源结构时,在这种情况下你可能需要向前引用.
    1 <Window x:Class="Wpf.Resource"
    2 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    3 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    4 Title="Resource">
    5 <Grid>
    6 <StackPanel>
    7 <Label Content="{DynamicResource lbl}" />
    8 </StackPanel>
    9 </Grid>
    10 <Window.Resources>
    11 <ContentControl x:Key="lbl">Hello, World!</ContentControl>
    12 </Window.Resources>
    13  </Window>
               上图代码,如果是静态资源引用会出错(因为静态引用不支持向前引用).
            动态资源引用存在一些限制,要设置的属性必须是FrameworkElement或FrameworkContentElement上的属性.DependencyProperty必须支持该属性.引用针对Style Setter 中的某个值.
    • 其他

          资源合并

          资源A:

    1 <ResourceDictionary
    2 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    3 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    4 <ContentControl x:Key="A">Hello, World!</ContentControl>
    5  </ResourceDictionary>

          资源B:

    <ResourceDictionary
    xmlns
    ="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x
    ="http://schemas.microsoft.com/winfx/2006/xaml">
    <ContentControl x:Key="B">Hello, WPF!</ContentControl>
    </ResourceDictionary>

         合并:

    1 <Window x:Class="Wpf.Resource"
    2 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    3 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    4 Title="Resource">
    5 <Window.Resources>
    6 <ResourceDictionary>
    7 <ResourceDictionary.MergedDictionaries>
    8 <ResourceDictionary Source="A.xaml" />
    9 <ResourceDictionary Source="B.xaml" />
    10 </ResourceDictionary.MergedDictionaries>
    11 </ResourceDictionary>
    12 </Window.Resources>
    13 <Grid>
    14 <StackPanel>
    15 <Label Content="{DynamicResource A}" />
    16 <Label Content="{DynamicResource B}" />
    17 </StackPanel>
    18 </Grid>
    19  </Window>

          如果存在重复的键,那么以后者为准.

          资源共享

          有时候需要修改x:Shared的值,确保每次引用都是一个新的实例.

    1 <Window.Resources>
    2 <Image x:Key="image" x:Shared="False" Source="/image.jpg" />
    3 </Window.Resources>
    4 <Grid>
    5 <StaticResource ResourceKey="image" />
    6 <StaticResource ResourceKey="image" />
    7 </Grid>
  • 相关阅读:
    JavaScript Array 对象方法
    前后台如何转码
    nrm 的使用说明
    sass的学习笔记
    前端书籍概述;
    程序员必读书籍及导读指南
    HTML5之FileReader的使用
    jQery的方法
    jQuery的使用说明
    div,contenteditable编辑器之ctrl+enter换行,enter发送
  • 原文地址:https://www.cnblogs.com/kingge/p/2034947.html
Copyright © 2011-2022 走看看