首页 文章

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

提问于
浏览
29

在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 回答

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

  • 23

    最佳解决方案是在资源字典中将 add a dummy default style 合并到一起 .

    <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}}" />
    
  • 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

相关问题