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

时间:2010-05-02 13:43:35

标签: 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>

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>

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>

3 个答案:

答案 0 :(得分: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}}" />

答案 1 :(得分:4)

当不使用startupuri时app.xaml中的application.resources中存在单一样式时,这可能是由已知错误引起的。

修复是添加这样的其他样式......

...
   <Style x:Key="unused" />
</Application.Resources>

有关详细信息,请查看此链接.... http://bengribaudo.com/blog/2010/08/19/106/bug-single-application-resources-entry-ignored

答案 2 :(得分:1)

有一种解决方法,但我只能使它在窗口级别(而不是应用程序级别)工作。

为了从单独的项目中包含WPF 4.0资源,必须将资源作为资源添加到窗口的代码中。该语句属于窗口的构造函数,在InitializeComponent方法调用之前:

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

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

我会详细了解此问题here

相关问题