简体   繁体   中英

WPF : Extend Theme's style - StackOverflowException

I want every button to have 5 points margin, in addition to Royale theme style.

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>

It compiles but I get:

An unhandled exception of type 'System.StackOverflowException' occurred in PresentationFramework.dll

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

There are no exception details because:

{Cannot evaluate expression because the current thread is in a stack overflow state.}

This seems to be a circular reference between your style and the one defined in PresentationFramework.Royale. A workaroud would be to place resources at different levels:

<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>

请查看此问题以及对另一个解决方案的回答 ,该解决方案不需要您在每个窗口中指定资源字典,并允许您动态地解析BasedOn样式。

I would remove the BasedOn attribute - it's not necessary. Think of it this way, merging the Royale theme will apply the button theme, and you just want to change the margin - styles are additive in nature, so it will combine the Royale theme and your own button theme without specifying the BasedOn attribute - does that make sense?

Cheers!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM