【发布时间】:2017-04-11 06:32:20
【问题描述】:
我在 WPF 窗口中有这段代码:
<Window.Resources>
<Style x:Key="MahappsStyle">
<Style.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Fonts.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Colors.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/Blue.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/BaseLight.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Style.Resources>
</Style>
</Window.Resources>
这个想法是在我的应用程序中为单个元素启用字典中的外部样式。例如,它应该通过将样式“MahappsStyle”应用于名为“HamburgerMenu”的元素来工作:
<mahapps:HamburgerMenu x:Name="hamburgerMenu" Style="{StaticResource MahappsStyle}"
DisplayMode="CompactOverlay">
</mahapps:HamburgerMenu>
但这种方法似乎只在设计器中有效,而在运行时无效。我错过了什么?有没有其他方法可以将 MergedDictionaries 设置为单个元素?
更新。找到了方法。首先需要在应用程序中创建 Mahapps.xaml,内容如下:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mahapps="http://metro.mahapps.com/winfx/xaml/controls"
xmlns:local="clr-namespace:Promt.Desktop">
<ResourceDictionary.MergedDictionaries >
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.xaml"/>
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Fonts.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Colors.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/Blue.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/BaseLight.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
然后可以通过以下方式应用于单个元素:
<mahapps:HamburgerMenu>
<mahapps:HamburgerMenu.Resources>
<ResourceDictionary Source="pack://application:,,,/Promt.Desktop;component/Styles/Mahapps.xaml"/>
</mahapps:HamburgerMenu.Resources>
</mahapps:HamburgerMenu>
我真的很失望 ResourceDictionary 不能保存 x:key 属性。如果有人知道另一种方法 - 请发布。
UPDATE2. 来自 Evk 的更好的解决方案(基于 Laith 的回答)。
【问题讨论】:
-
从
HamburgerMenu中删除样式tag并将样式文件合并到app.xaml 文件中 -
@DarshanPatel 这不是我想要的 - 在这种情况下,样式将应用于所有应用程序元素,包括按钮、复选框等。这就是如何避免这种情况的问题所在