WPF资源基础笔记

来源:互联网 发布:阿里云收件服务器 编辑:程序博客网 时间:2024/05/02 04:23

资源

WPF资源系统是一种保管一系列有用对象的简单方法,从而可以更容易的重用这些对象。

应用程序资源和程序集资源是不同的概念。

应用程序资源:可在应用程序中的其他部分使用。

程序集资源:是一块嵌入到编译过的程序集中的二进制数据

资源的有点:

高效,可维护,适应性。

前台标记资源

<Windows.Resources>

<资源标记>

<ImageBrush x:Key=”资源名称”......../>

</Windows.Resources>

使用

<Button Backgroud=”StaticResources 资源名称”/>

每一个元素都有一个Resources属性。合理定义资源的位置对重用资源有重要的意义。

如果在一个元素中放置资源,需要稍微重新排列标记,在设定背景之前定义资源

<Button Width="40" Height="40" Background="{StaticResource ResourceKey=TileBrush}" VerticalAlignment="Top"/>

<Button Width="40" Height="40" VerticalAlignment="Center">

            <Button.Resources>

                <ImageBrush x:Key="TilefBrush" ImageSource="Images/.jpg"/>

            </Button.Resources>

            <Button.Background>

                <StaticResource ResourceKey= "TilefBrush"/>

            </Button.Background>

        </Button>

通过代码访问资源

通过FindResource(“资源键名”);此方法找到合适的资源,可使用TryFindResource方法代替,如果找不到资源时返回null

应用程序资源,这些资源在App.xaml中。

系统资源

动态资源主要是用于辅助应用程序对系统环境设置的变化做出相应,但是开始时如何检测系统环境设置,并在代码中使用。

常用的类有

SystemColorsSystemFonts,和SystemParameters这些类都在System.Windows名称空间中

lable.Foreground = new SolidColorBrush(SystemColors.WindowTextColor);

            lable.Foreground = SystemColors.WindowTextBrush;

WPF中可使用静态

<Label Name="lable" Content="我是一些系统资源" VerticalAlignment="Bottom" Foreground="{x:Static SystemColors.WindowTextBrush}"/>

资源字典

如果希望在多个项目之间共享资源,可以创建资源字典。

步骤是:

选择新建项=》选择资源字典

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <ImageBrush x:Key="brush" ImageSource="Images/.jpg"/>

</ResourceDictionary>

资源字典使用

<Application x:Class="WPF10_1_2_1.App"

             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

             StartupUri="MainWindow.xaml">

    <Application.Resources>

        <ResourceDictionary>

            <ResourceDictionary.MergedDictionaries>

                <ResourceDictionary Source=""/>

            </ResourceDictionary.MergedDictionaries>

        </ResourceDictionary>

    </Application.Resources>

</Application>

0 0