我有一个设计 WPF 按钮的文件 MyButtonStyles.xaml。这个文件使用一个样式来设置一些颜色和字体:
<ResourceDictionary xmlns......>
<Style BasedOn="{StaticResource {x:Type Button}} TargetType="{x:Type Button}">
<Setter Property="Foreground" Value="Blue" />
<Setter Property="FontSize" Value="22" />
</Style>
</ResourceDictionary>
Run Code Online (Sandbox Code Playgroud)
此按钮用于两个 xaml 文件。一个显示按上述样式设计的按钮。这是自动发生的,因为上面的样式有对应的TargetType并且没有x:Key属性。
在另一个 xaml 文件中,我也使用了这个按钮,但是上面的样式应该由另一个 setter 属性扩展。通过合并字典并基于它工作的原始样式来做到这一点:
<ResourceDictionary>
<ResourceDictionary.MergedDictionary>
<ResourceDictionary Source="MyButtonStyles.xaml" />
<ResourceDictionary.MergedDictionary>
<Style BasedOn="ButtonStylesOrig" TargetType="{x:Type Button}">
<Setter Property="Background" Value="Green" />
</Style>
</ResourceDictionary>
Run Code Online (Sandbox Code Playgroud)
但为此,我必须向x:Key基本样式添加一个属性 (ButtonStylesOrig)。这意味着在第一个使用按钮的 xaml 中,将不再应用基本样式。
是否有可能在不失去全局范围的情况下扩展样式(例如不使用x:Key)?
这有效:
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="MyButtonStyles.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
<Grid>
<Grid.Resources>
<Style TargetType="{x:Type Button}" BasedOn="{StaticResource {x:Type Button}}">
<Setter Property="Background" Value="Green" />
</Style>
</Grid.Resources>
<Button Content="Button" />
</Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)
关键是不要覆盖您将基本样式合并到的同一资源字典中的资源:
| 归档时间: |
|
| 查看次数: |
683 次 |
| 最近记录: |