【问题标题】:WPF : Extend Theme's style - StackOverflowExceptionWPF:扩展主题的样式 - StackOverflowException
【发布时间】:2009-05-29 17:42:59
【问题描述】:

除了 Royale 主题样式之外,我希望每个按钮都有 5 点边距。

Window1.xaml:

<Window x:Class="_styles.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
  <Window.Resources>
    <ResourceDictionary>
      <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="/PresentationFramework.Royale;component/themes/royale.normalcolor.xaml" />
      </ResourceDictionary.MergedDictionaries>
      <Style TargetType="{x:Type Button}" BasedOn="{StaticResource {x:Type Button}}">
        <Setter Property="Margin" Value="5"/>
      </Style>
    </ResourceDictionary>
  </Window.Resources>
  <StackPanel>
    <Button Content="Button A"/>
    <Button Content="Button B"/>
  </StackPanel>
</Window>

它编译但我得到:

PresentationFramework.dll 中出现“System.StackOverflowException”类型的未处理异常

public Window1() {
    InitializeComponent(); // <-- getting exception here
}

没有异常详情,因为:

{无法计算表达式,因为当前线程处于堆栈溢出状态。}

【问题讨论】:

  • 您能告诉我们异常是在哪里引发的吗?

标签: wpf themes styles


【解决方案1】:

这似乎是您的样式与 PresentationFramework.Royale 中定义的样式之间的循环引用。一种解决方法是将资源放在不同的级别:

<Window x:Class="_styles.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"    Title="Window1" Height="300" Width="300">
<Window.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/PresentationFramework.Royale;component/themes/royale.normalcolor.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Window.Resources>
<StackPanel>
    <StackPanel.Resources>
        <Style TargetType="{x:Type Button}" BasedOn="{StaticResource {x:Type Button}}">
            <Setter Property="Margin" Value="5"/>
        </Style>
    </StackPanel.Resources>
    <Button Content="Button A"/>
</StackPanel>
</Window>

【讨论】:

  • 谁能解释这是如何导致循环引用的以及为什么更改范围可以解决它?
【解决方案2】:

我会删除 BasedOn 属性 - 这不是必需的。这样想,合并 Royale 主题将应用按钮主题,而您只想更改边距 - 样式本质上是相加的,因此它将结合 Royale 主题您自己的按钮主题不指定 BasedOn 属性 - 这有意义吗?

干杯!

【讨论】:

  • 我的印象是范围更近的样式覆盖以前的样式,即最多可以应用一种样式。而BasedOn属性是extend一种风格的方式。
  • 啊,你说得对。这很有趣——我尝试了我给你的建议,使用 Aero 主题,省略 BasedOn="..." 将按钮样式重置为原始 XP 主题。 Woops :) 如果您可以分享更多来源,也许我可以看看。
【解决方案3】:

请参阅this questionmy answer 了解另一个不需要您在每个窗口中指定资源字典并允许您动态解析 BasedOn 样式的解决方案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-14
    • 1970-01-01
    • 1970-01-01
    • 2014-05-09
    • 1970-01-01
    • 2013-02-02
    相关资源
    最近更新 更多