WPF没有应用MergedDictionaries中定义的默认样式?

Bur*_*ger 29 c# wpf .net-4.0

在WPF应用程序中,我在单独的资源字典中定义了默认控件样式(例如"ButtonStyle.xaml"),并将它们作为合并字典添加到名为"ResDictionary.xaml"的资源字典中.

如果我在我的App.xaml中将此"ResDictionary.xaml"称为合并字典,则不会应用默认样式.但是,如果我引用"ButtonStyle.xaml",它可以正常工作.

如果我在.NET 3.5或3.0中重新编译相同的代码,它会识别并应用"App.xaml"到"ResDictionary.xaml"中引用的默认样式,但不能在.NET 4.0中应用.

在运行时,如果我检查Application.Current.Resources字典,那么默认样式就在那里,但只有在Button控件中显式指定Style属性时才会应用它们.

是否有任何解决方案在.NET 4.0中以这种方式引用资源字典(包含默认样式)?


App.xaml中:

<Application.Resources>
  <ResourceDictionary>
    <ResourceDictionary.MergedDictionaries>
      <ResourceDictionary Source="Styles/ResDictionary.xaml"/>
    </ResourceDictionary.MergedDictionaries>
  </ResourceDictionary>
</Application.Resources>
Run Code Online (Sandbox Code Playgroud)

ResDictionary.xaml:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="Default/ButtonStyle.xaml"/>
    </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
Run Code Online (Sandbox Code Playgroud)

ButtonStyle.xaml:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Style TargetType="Button">
        <Setter Property="Background" Value="Yellow"/>
    </Style>
</ResourceDictionary>
Run Code Online (Sandbox Code Playgroud)

小智 23

最佳解决方案是在资源字典中添加虚拟默认样式,将所有资源合并在一起.

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

<ResourceDictionary.MergedDictionaries>
    <ResourceDictionary Source="Style/Button.xaml"/>
</ResourceDictionary.MergedDictionaries>

<Style TargetType="Control" BasedOn="{StaticResource {x:Type Control}}" />
Run Code Online (Sandbox Code Playgroud)


小智 1

有一个解决这个问题的办法,但我\xe2\x80\x99ve只能让它在窗口级别(而不是应用程序级别)工作。

\n\n

为了包含来自单独项目的 WPF 4.0 资源,必须将该资源作为资源添加到window\xe2\x80\x99s代码后面。该语句属于 window\xe2\x80\x99s 构造函数,位于 InitializeComponent 方法调用之前:

\n\n
public ControlsWindow()\n{\n    this.Resources = Application.LoadComponent(new Uri("[WPF 4.0 ResourceProjectName];Component/[Directory and File Name within project]", UriKind.Relative)) as ResourceDictionary;\n    InitializeComponent();\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

注意:将“[WPF 4.0 ResourceProjectName]”文本替换为资源的项目名称。此外,“[项目内的目录和文件名]”需要替换为资源文件的相对位置(如“Themes/StandardTheme.xaml”)

\n\n

我在这里详细讨论这个问题。

\n