0501资源封装字典与资源查找

一、资源字典

1、添加资源字典文件ResDictionary.xaml

属性是页

 2、把放在窗口里面的对象资源挪到这里,命名空间也要添加

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:sys="clr-namespace:System;assembly=mscorlib"
                    xmlns:model="clr-namespace:WpfApp1.Model">
    <sys:Double x:Key="value">200</sys:Double>
    <x:Array x:Key="datas" Type="sys:Int32">
        <sys:Int32>1</sys:Int32>
        <sys:Int32>2</sys:Int32>
        <sys:Int32>3</sys:Int32>
        <sys:Int32>4</sys:Int32>
        <sys:Int32>5</sys:Int32>
    </x:Array>
    <model:MyValueModel x:Key="my" MyProperty="123" Value="tom"/>
</ResourceDictionary>

 3、在窗口中引用这个资源字典文件

    <Window.Resources>
        <ResourceDictionary Source="/ResDictionary.xaml"></ResourceDictionary>
    </Window.Resources>

或者全路径:<ResourceDictionary Source="pack://application:,,,/WpfApp1;component/ResDictionary.xaml"></ResourceDictionary>

 

二、资源查找

自身--》父级---》窗口》应用程序资源--》框架系统资源

一层层的向上找

如果<Window.Resources>页签里面也没有

还会去app.xaml里面查找

    <Application.Resources>
        <ResourceDictionary Source="pack://application:,,,/WpfApp1;component/ResDictionary.xaml"></ResourceDictionary>
    </Application.Resources>

可以在所有的窗口生效

作用域的问题,对子项起作用

 

框架系统资源,wpf源码定义的静态类资源

1、Background="{x:Static SystemColors.ActiveBorderBrush}"

背景色、前景色都是画刷Brush定义的,比单纯的colors更灵活,还可以画图像到画布

2、key方式资源,返回是是color不是brush要转换一下

            <Border.Background>
                <SolidColorBrush  Color="{DynamicResource {x:Static SystemColors.ActiveBorderColorKey}}"/>
            </Border.Background>

用的少,会自己定义,只是要知道这样引用系统资源的方式

重用原则
被广泛的重用,可以使用应用程序资源
两三个窗口使用资源,建议在各个窗口分别定义

 

三、多个资源字典的引用

合并多个资源字典文件ResourceDictionary.MergedDictionaries,使用比较常见

比如引入外部的样式或者模板,都是使用资源字典的形式,有按钮的、文本框的……多个资源字典必须合并引用

    <Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="pack://application:,,,/WpfApp1;component/ResDictionary.xaml"></ResourceDictionary>
                <ResourceDictionary Source="pack://application:,,,/WpfApp1;component/ResDictionary2.xaml"></ResourceDictionary>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Window.Resources>

引用<TextBlock Text="{StaticResource text}"/>

多个字典中的变量名称类型不能冲突,都是value不能同时被int或string引用

如果是重名的变量

 

 

后面的会覆盖前面的

2在前,2中的hello就会被1中的zys所覆盖,页面显示zys

 

posted on 2025-04-04 23:12  张彦山  阅读(28)  评论(0)    收藏  举报