【问题标题】:Style inheritance based on different XAML基于不同 XAML 的样式继承
【发布时间】:2012-04-30 08:27:31
【问题描述】:

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

如何做到这一点?

【问题讨论】:

    标签: c# .net wpf xaml resourcedictionary


    【解决方案1】:

    简单的方法:

    Dictionary2.xaml 中定义MergedDictionaries(紧跟在ResourceDictionary 标签之后):

    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="/Path/to/Dictionary1.xaml" />
    </ResourceDictionary.MergedDictionaries>
    

    然后

    <Style x:Key="headerStyle" TargetType="TextBlock" BasedOn="{StaticResource basicStyle}" >
        .....
    </Style>
    

    这将解决问题,但与所有简单的解决方案一样,有一个问题:每次合并字典时,您都会有效地创建合并字典的副本。它是递归的 - 如果您有 Dict3.xaml 和 Dict4.xaml 都加载 Dictionary2.xaml,您将创建 Dictionary1.xaml 的三个实例。通过复杂的依赖结构,您可以在应用程序启动时在内存中拥有 19,000 多个字典对象,并且内存占用从 180MB 到 1200MB (TrueStory™ :( )。

    解决方案是SharedResourceDictionary。本教程中的实现应该被视为一个起点,并且可能需要进行一定程度的调整 - 取决于使用场景。谷歌“wpf SharedResourceDictionary”了解一些问题和解决方案。

    【讨论】:

    • 我在寻找完全相同的东西。暂时我会用最简单的方法,也继续探索SharedResourceDictionary。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-24
    • 2020-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多