WPF学习之引用资源

原文: WPF学习之引用资源

复制代码
<!--
    资源基础:保管一系列对象,做到重用对象。
    优点:1、具有高效性,通过定义资源可以在标记的多个地方试用,使得代码精简。
          2、可维护性。创建资源相当于在程序中创建常量。
          3、适用性。特定的信息和应用程序其他部分分离,并且放置在资源中,可以动态的修改。     
-->
<Window.Resources>
    <!--同一级别下  资源名不能相同-->
    <ImageBrush x:Key="TileBrush" TileMode="Tile" ViewportUnits="Absolute" Viewport="0 0 30 30" ImageSource="Image/Icon.png" ></ImageBrush>
</Window.Resources>
<StackPanel>
    <!--每个元素都有自己的资源,每个元素都可以访问自身及其元素树上父类的资源,先访问自身的资源-->
   <!--也可以将资源放置在App.xmal文件中,因为App.xmal文件是整个应用程序的顶层--> <!--静态资源(StaticResource)需要在引用之前定义好资源--> <Button Margin="3" Name="button1" FontSize="14" Padding="5" Background="{StaticResource TileBrush}">Static Resource</Button> <Button Margin="3" Name="button2" FontSize="14" Padding="5" > <Button.Resources> <ImageBrush x:Key="SelfTileBrush" TileMode="FlipX" ViewportUnits="Absolute" Viewport="0 0 30 30" ImageSource="Image/Icon.png" ></ImageBrush> </Button.Resources> <Button.Background><!--使用自身的资源 需要在定义的资源之后引用资源--> <StaticResource ResourceKey="SelfTileBrush"></StaticResource> </Button.Background> <Button.Content>Myself Resource</Button.Content> </Button> <Button Margin="3" Name="button3" FontSize="14" Padding="5" Background="{DynamicResource TileBrush}">Dynamic Resource</Button> <!-- 点击事件中放入以下代码,就可以实现动态修改资源。但修改的资源仅用于标记为DynamicResource的引用元素。此处是button3改变,button1不改变 this.Resources["TileBrush"] = new SolidColorBrush(Colors.SkyBlue); --> <Button Margin="3" Name="button4" FontSize="14" Padding="5" Click="button4_Click">Change Resource</Button> <!--引用系统的资源。需要使用动态资源,以方便系统修改后,程序作出改变。但其资源又是静态的,所以需要标记为静态引用,均需要在后面添加一个Key--> <Button Margin="3" Name="button5" FontSize="14" Foreground="{DynamicResource {x:Static SystemColors.WindowTextBrushKey}}" Padding="5" >Change Resource</Button> </StackPanel>
复制代码

猜你喜欢

转载自www.cnblogs.com/lonelyxmas/p/12749275.html