WEB开发网
开发学院WEB开发ASP.NET WPF学习笔记7. Resource 阅读

WPF学习笔记7. Resource

 2010-10-11 16:19:14 来源:本站整理   
核心提示:资源查找: 引用逻辑资源时首先会查找父元素 Resources 集合,如未找到,WPF学习笔记7. Resource(3),会逐级检查更上层的父元素,如果直到根元素依然未找到有效的逻辑资源定义,因此它不能像静态资源那样引用一个完整的元素对象,<Windowx:Class="Learn.WPF.Windo

资源查找: 引用逻辑资源时首先会查找父元素 Resources 集合,如未找到,会逐级检查更上层的父元素。如果直到根元素依然未找到有效的逻辑资源定义,那么 WPF 会检查 Application.Resources (App.xaml 中定义) 和系统属性集合(SystemParamters 等)。每个独立的资源字典中键名不能重复,但在多个不同层级的资源字典中允许重复,离资源引用最近的那个逻辑资源项被优先采纳。

<Window x:Class="Learn.WPF.Window1"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title="Window1">
  <Window.Resources>
    <Label x:Key="label1" Content=" Hello, World!" />
  </Window.Resources>
  <Grid>
    <Grid.Resources>
      <Label x:Key="label1" Content=" Hello, C#!" />
    </Grid.Resources>
    <StackPanel>
      <StaticResource ResourceKey="label1" />
    </StackPanel>
  </Grid>
</Window>

将显示 "Hello, C#!"。

逻辑资源的引用方式又分类 "静态(StaticResource)" 和 "动态(DynamicResource)" 两种方式,区别在于静态引用仅在第一次资源加载时被应用,而动态引用则会在资源被更改时重新应用。

<Window x:Class="Learn.WPF.Window1"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title="Window1">
  <Window.Resources>
    <ContentControl x:Key="label1" x:Shared="False">Hello, World!</ContentControl>
  </Window.Resources>
  <x:Code>
    private void button1_Click(object sender, RoutedEventArgs e)
    {
      this.Resources["label1"] = "Hello, C#!";
    }
  </x:Code>
  <Grid>
    <StackPanel>
      <Label x:Name="label1" Content="{StaticResource label1}" />
      <Label x:Name="label2" Content="{DynamicResource label1}" />
      <Button x:Name="button1" Click="button1_Click">Test</Button>
    </StackPanel>
  </Grid>
</Window>

单击按钮后,你会发现 label2 实时反应了资源的修改。

动态资源只能用于设置依赖属性值,因此它不能像静态资源那样引用一个完整的元素对象。

<Window x:Class="Learn.WPF.Window1"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title="Window1">
  <Window.Resources>
    <Label x:Key="label" x:Shared="False" Content="Hello, World!" />
  </Window.Resources>
  <Grid>
    <StackPanel>
      <DynamicResource ResourceKey="label" />
    </StackPanel>
  </Grid>
</Window>

这将导致出现下图这样的异常,而静态资源则没有这个问题。

上一页  1 2 3 4  下一页

Tags:WPF 学习 笔记

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接