- StaticResource uses first value. DynamicResource uses last value.
- DynamicResource can be used for nested styling, StaticResource cannot.
假设您有这个嵌套样式字典。LightGreen在根级别,而Pink嵌套在一个Grid中。
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style TargetType="{x:Type Grid}">
<Style.Resources>
<Style TargetType="{x:Type Button}" x:Key="ConflictButton">
<Setter Property="Background" Value="Pink"/>
</Style>
</Style.Resources>
</Style>
<Style TargetType="{x:Type Button}" x:Key="ConflictButton">
<Setter Property="Background" Value="LightGreen"/>
</Style>
</ResourceDictionary>
在视图中:
<Window x:Class="WpfStyleDemo.ConflictingStyleWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="ConflictingStyleWindow" Height="100" Width="100">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Styles/ConflictingStyle.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
<Grid>
<Button Style="{DynamicResource ConflictButton}" Content="Test"/>
</Grid>
</Window>
StaticResource将把按钮呈现为LightGreen,其中它找到的样式的第一个值。DynamicResource将覆盖LightGreen按钮,同时呈现网格为Pink。
StaticResource
DynamicResource
请记住,VS Designer 将 DynamicResource 视为 StaticResource。 它将获取第一个值。 在这种情况下,虽然实际颜色为 Pink,但 VS Designer 将以 LightGreen 的颜色呈现按钮。
当移除根级样式(LightGreen)时,StaticResource 将会抛出错误。