WPF入门-3.资源作用域

WPF 入门(三):资源作用域(Resource Scope)

WPF 资源有多种作用域(层级),决定了资源的可见范围和优先级。常见资源作用域如下:

作用域 说明
控件级 仅对单个控件有效,直接在控件属性或 Resources 中定义
用户控件级 仅对 UserControl 及其子元素有效,定义在 <UserControl.Resources>
页面级 仅对 Page 及其子元素有效,定义在 <Page.Resources>
窗口级 仅对 Window 及其子元素有效,定义在 <Window.Resources>
应用级 对整个应用有效,定义在 <Application.Resources>
外部资源字典 独立的 ResourceDictionary 文件,可被其他作用域合并引用

控件级资源(Local Resource)

拥有最高的优先级。 如下,将按钮的背景色设置为红色:

1
<Button Content="Button 1" Width="100" Height="50" Background="Yellow" />

用户控件级资源(UserControl-level Resource)

定义在 <UserControl.Resources> 内,仅对该用户控件及其子元素有效。 如下,为用户控件内所有 Button 设置背景色为黄色:

1
2
3
4
5
6
7
<UserControl.Resources>
<Style TargetType="Button">
<Setter Property="Width" Value="100"/>
<Setter Property="Height" Value="50"/>
<Setter Property="Background" Value="Yellow"/>
</Style>
</UserControl.Resources>

页面级资源(Page-level Resource)

定义在 <Page.Resources> 内,仅对该页面及其子元素有效。

1
2
3
4
5
6
7
<Page.Resources>
<Style TargetType="Button">
<Setter Property="Width" Value="100"/>
<Setter Property="Height" Value="50"/>
<Setter Property="Background" Value="Yellow"/>
</Style>
</Page.Resources>

窗口级资源(Window-level Resource)

需要写在 <Window.Resources> 标签内,样式只能作用于当前窗口内的控件。

1
2
3
4
5
6
7
<Window.Resources>
<Style TargetType="Button">
<Setter Property="Width" Value="100"/>
<Setter Property="Height" Value="50"/>
<Setter Property="Background" Value="Yellow" />
</Style>
</Window.Resources>

应用级资源(Application-level Resource)

需要写在 <Application.Resources> 标签内,能作用于当前应用内所有窗口中控件的样式。

1
2
3
4
5
6
7
<Application.Resources>
<Style TargetType="Button">
<Setter Property="Width" Value="100"/>
<Setter Property="Height" Value="50"/>
<Setter Property="Background" Value="Yellow" />
</Style>
</Application.Resources>

外部资源字典(ResourceDictionary File)

可将资源单独存放在 .xaml 文件中,通过 MergedDictionaries 合并到任意作用域,实现资源共享。

1
2
3
4
5
6
7
<ResourceDictionary>
<Style TargetType="Button">
<Setter Property="Width" Value="100"/>
<Setter Property="Height" Value="50"/>
<Setter Property="Background" Value="Yellow" />
</Style>
</ResourceDictionary>

在 App.xaml 或 Window/Page 中引用:

1
2
3
4
5
6
7
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Resources/MyResource.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>

资源查找顺序:WPF 会从控件级开始,逐级向上查找(控件 → 用户控件 → 页面 → 窗口 → 应用 → 外部资源字典),直到找到为止。

PS: 与HTML不同, WPF从控件向上找, 找到就会停止. HTML(CSS)的样式查找是反过来的, 是从上往下的。浏览器会从外层(如外部样式表、head 内 style、继承的样式)到内层,逐步应用样式。 如果有多个规则匹配同一元素,则根据“优先级(Specificity)”和“后出现覆盖前出现”的原则决定最终样式。