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

WPF学习笔记7. Resource

 2010-10-11 16:19:14 来源:本站整理   
核心提示:2. 逻辑资源逻辑资源是一些存储在元素 Resources 属性中的对象,这些 "预定义" 的对象被一个或多个子元素所引用或共享,WPF学习笔记7. Resource(2),<Windowx:Class="Learn.WPF.Window1"xmlns="http

2. 逻辑资源

逻辑资源是一些存储在元素 Resources 属性中的对象,这些 "预定义" 的对象被一个或多个子元素所引用或共享。

<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">Hello, World!</ContentControl>
    <ImageSource x:Key="image1">/a.png</ImageSource>
  </Window.Resources>
  <Grid>
    <Label Content="{StaticResource label1}" />
    <Image Source="{StaticResource image1}" />
  </Grid>
</Window>

当然,我们也可以写成下面这种格式。

<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">Hello, World!</ContentControl>
    <ImageSource x:Key="image1">/a.png</ImageSource>
  </Window.Resources>
  <Grid>
    <Label>
      <Label.Content>
        <StaticResource ResourceKey="label1" />
      </Label.Content>
    </Label>
    <Image>
      <Image.Source>
        <StaticResource ResourceKey="image1" />
      </Image.Source>
    </Image>
  </Grid>
</Window>

我们甚至可以用逻辑资源定义一个完整的子元素。

<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!" />
    <Image x:Key="image1" Source="/a.png" />
  </Window.Resources>
  <Grid>
    <StaticResource ResourceKey="label1" />
    <StaticResource ResourceKey="image1" />
  </Grid>
</Window>

逻辑资源有个限制,那就是这些继承自 Visual 的元素对象只能有一个父元素,也就是说不能在多个位置使用,因为多次引用的是同一个对象实例。

<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>
    <Image x:Key="image1" Source="/a.png" />
  </Window.Resources>
  <Grid>
    <StaticResource ResourceKey="image1" />
    <StaticResource ResourceKey="image1" />
  </Grid>
</Window>

你将看到下面这样一个错误提示。

解决方法就是添加 "x:Shared=False",这样每次引用都会生成一个新的逻辑资源对象。

<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>
    <Image x:Key="image1" x:Shared="False" Source="/a.png" />
  </Window.Resources>
  <Grid>
    <StaticResource ResourceKey="image1" />
    <StaticResource ResourceKey="image1" />
  </Grid>
</Window>

上一页  1 2 3 4  下一页

Tags:WPF 学习 笔记

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