如何将样式中的 BasedOn 标记指定为其他文件中定义的样式。
例子,
Dictionary1.xaml 定义
<Style x:Key="basicStyle" TargetType="TextBlock" >
<Setter Property="FontSize" Value="24"></Setter>
<Setter Property="Foreground" Value="DarkGray"></Setter>
<Setter Property="FontWeight" Value="Bold"></Setter>
</Style>
在 Dictionary2.xaml 中我需要类似的东西
<Style x:Key="headerStyle" TargetType="TextBlock" >
<Setter Property="FontSize" Value="46"></Setter>
<Setter Property="Foreground" Value="DarkGray"></Setter>
<Setter Property="FontWeight" Value="Bold"></Setter>
</Style>
如何实现?
最佳答案
简单的方法:
在 Dictionary2.xaml
中定义 MergedDictionaries(紧跟在 ResourceDictionary
标签之后):
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/Path/to/Dictionary1.xaml" />
</ResourceDictionary.MergedDictionaries>
然后
<Style x:Key="headerStyle" TargetType="TextBlock" BasedOn="{StaticResource basicStyle}" >
.....
</Style>
这将解决问题,但与所有简单的解决方案一样,有一个陷阱:每次合并词典时,您都会有效地创建合并词典的副本。而且它是递归的——如果您有同时加载 Dictionary2.xaml 的 Dict3.xaml 和 Dict4.xaml,您将创建三个 Dictionary1.xaml 实例。对于复杂的依赖结构,您可能会在应用程序启动时在内存中拥有 19,000 多个字典对象,内存占用量从 180MB 到 1200MB (TrueStory™ :( )。
解决方案是 SharedResourceDictionary .本教程中的实现应被视为一个起点,可能需要进行一定程度的调整——具体取决于使用场景。 Google“wpf SharedResourceDictionary”以获取一些问题和解决方案。
关于c# - 基于不同XAML的样式继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10380597/