继承自应用程序样式(WPF)

Nol*_*rin 4 wpf inheritance xaml styles

我试图Window在我的WPF应用程序中继承应用程序级别的样式,但是我很难让它继承而不是简单地覆盖现有的样式.

App.xaml(在下面App.Resources element)我定义了一个样式:

<Style TargetType="Button">
    <Setter Property="Padding" Value="6"/>
    <Setter Property="FontWeight" Value="Bold"/>
</Style>
Run Code Online (Sandbox Code Playgroud)

在XAML论坛中Window,我定义了以下内容Window.Resources:

<Style TargetType="Button" BasedOn="{StaticResource {x:Type Button}}">
    <Setter Property="Padding" Value="6"/>
    <Setter Property="FontWeight" Value="Bold"/>
</Style>
Run Code Online (Sandbox Code Playgroud)

这里的问题是前一个(app)样式被忽略,好像后一个(窗口)样式已经覆盖它.该BasedOn属性已设置,旨在表明应该继承现有样式,据我所知.删除属性也无济于事.我能想到的唯一潜在原因是{StaticResource {x:Type Button}}只引用了默认的WPF样式而不是我在App.xaml中定义的样式.

我知道使用该x:Key属性可以实现这种样式行为,但我希望有一种更优雅的方式,允许我将具有继承的样式应用于范围内的所有控件(即应用程序/窗口).

更新

感谢您的回复.你确实在样本应用程序中按预期工作是对的.不同之处在于我无意中没有提到样式App.xaml包含在a中ResourceDictionary,因此:

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>

            <ResourceDictionary Source="SettingsDictionary.xaml"/>

            <ResourceDictionary>

                <Style x:Key="DefaultButton" TargetType="Button">
                    <Setter Property="Padding" Value="4"/>
                    <Setter Property="HorizontalAlignment" Value="Center"/>
                    <Setter Property="VerticalAlignment" Value="Center"/>
                </Style>

            </ResourceDictionary>

        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>
Run Code Online (Sandbox Code Playgroud)

关于在这种情况下如何纠正问题的任何建议?

Ken*_* K. 5

编辑

经过一些研究,我发现如果设置了TargetType,则会自动生成x:Key.所以,App.xaml中的样式是正确的.但是,wpf设计器缺乏一些资源处理技能,并且不显示这两种样式.如果您构建并运行项目,则将应用这两种样式.

如果您的机器和VS2008的行为与我测试您的代码的行为相似.

希望这可以帮助.

编辑2

App.xaml中的资源和合并词典一直很古怪.我通过将第一个样式声明从合并字典中移出来解决了这个问题,如下所示:

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>

            <!--<ResourceDictionary Source="SettingsDictionary.xaml"/>-->

        </ResourceDictionary.MergedDictionaries>

        <Style TargetType="Button">
            <Setter Property="Foreground" Value="Red"/>
            <Setter Property="Padding" Value="4"/>
            <Setter Property="HorizontalAlignment" Value="Center"/>
            <Setter Property="VerticalAlignment" Value="Center"/>
        </Style>

    </ResourceDictionary>
</Application.Resources>
Run Code Online (Sandbox Code Playgroud)

另请注意,为样式提供除此之外的显式设置键{x:Type Button}将使其成为非默认样式,并使其不会自动应用.

通常建议仅为来自另一个文件的资源指定合并的字典,并在默认空间中指定编码资源,如上所述.