c# - 基于不同XAML的样式继承

标签 c# .net wpf xaml resourcedictionary

如何将样式中的 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/

相关文章:

c# - 使用 AJAX 动态加载 ASCX 控件

c# - 防止点击 toast 通知时再次打开应用程序

.net - 找出计算机何时不使用

WPF:将 Ctrl+Enter 转换为在 TextBox 上输入

wpf - 如何配置 NBug 发送邮件

c# - httpClient 告诉我错误 c# winform

c# - 来自 MVC View 页面的带有 <li> 元素的 POST <ul>

.net - 写入数据库时​​使用 DateTime.Now 时的 Incercept

c# - .net 路由开头的可选参数

c# - 如何在 WPF 的 Datagrid 行标题中居中对齐行号