混合通用的WPF样式和ResourceDictionary

8

我曾从事网站开发和WinForms,现在转向WPF,但可能还没有完全掌握其概念。

我可以在app.xaml中为我的应用程序定义通用样式,例如,在该文件中定义了我的所有Ribbon控件的样式。

然后,我尝试了Microsoft Blend,并学到了ResourceDictionary,这是一种类似于WinForms中 .resx 资源文件的资源文件。

但据我所知,这两个概念无法混合使用。例如,以下XAML代码将无法工作,因为ResourceDictionary必须是唯一的子元素。

<Application x:Class="Wpf.MyApplication.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:ribbon="clr-namespace:Microsoft.Windows.Controls.Ribbon;assembly=RibbonControlsLibrary"
             StartupUri="MyMainWindow.xaml">
    <Application.Resources>
        <!-- Resources scoped at the Application level should be defined here. -->
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Styles/RibbonStyle.xaml"/>
            </ResourceDictionary.MergedDictionaries>
            <BitmapImage x:Key="IconDokumentNeu" >Images/NewDocument_32x32.png</BitmapImage>
      <SolidColorBrush x:Key="LightGrayBrushKey">WhiteSmoke</SolidColorBrush>
    </ResourceDictionary>
    <Style TargetType="{x:Type ribbon:RibbonWindow}">
        <Setter Property="Icon" Value="../time2_32.png" />
        <Setter Property="TextOptions.TextFormattingMode" Value="Display" />
    </Style>
    </Application.Resources>
</Application>

看起来我没有真正理解这个概念。也许你可以帮助我,为什么这不可能,并且我如何在ResourceDictionary旁边使用通用样式。

2个回答

21

你已经在字典的“旁边”定义了资源,一张图片和一支画笔。

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <!-- Dictionaries from file here -->
        </ResourceDictionary.MergedDictionaries>

        <!-- Other resources here -->
    </ResourceDictionary>
</Application.Resources>

我知道,但是我是从MSDN的描述中得到的,ResourceDictionary中的样式必须有一个键。但是我想定义一些通用的样式而不需要键,这样它们就可以作为默认样式启用。 - René Stalder
@René:所以问题在于,如果您添加了与合并字典中的样式具有相同TargetType的样式,则会出现错误? - H.B.
不对。我只是不知道资源字典可以仅使用目标类型而不需要键来设置样式。直到现在... - René Stalder

5
只需在资源字典中包含{x:type}样式即可。
  <ResourceDictionary>
           <ResourceDictionary.MergedDictionaries> 
                   <!-- Dictionaries from file here -->  
           </ResourceDictionary.MergedDictionaries>    
           <Style TargetType="{x:Type ribbon:RibbonWindow}">         
               <Setter Property="Icon" Value="../time2_32.png" />         
               <Setter Property="TextOptions.TextFormattingMode" Value="Display" />  
           </Style> 
     </ResourceDictionary>  

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接