【发布时间】:2017-05-08 15:38:17
【问题描述】:
我有一个应用程序,它使用了几个可以在运行时切换的自定义主题。主题、应用程序和 UI(用户控件、对话框等)均位于单独的 .NET 程序集中。
主题不仅覆盖了控件的隐式默认样式(新控件模板),还提供了各种显式样式。
例子:
<!-- "Themes" assembly -->
<Style TargetType="Button" x:Key="DialogButtonStyle"
BasedOn="{StaticResource BaseButtonStyle}">
<Setter Property="HorizontalAlignment" Value="Left" />
<Setter Property="Height" Value="24" />
<Setter Property="MinWidth" Value="86" />
<Setter Property="Padding" Value="8 0" />
</Style>
<!-- "UI" assembly -->
<Button Style="{DynamicResource DialogButtonStyle}"
Content="OK" />
通过将所有样式、画笔等合并到应用程序资源中来应用主题,例如:
<Application x:Class="GUIDemo.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml">
<Application.Resources>
<ResourceDictionary x:Name="MainDictionary">
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary x:Name="ThemeDictionary">
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/Themes;component/SystemTheme.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
(或运行时对应的代码。)
问题:
是否可以在我的 UI 程序集(而不是应用程序程序集)中定义后备样式?如果应用程序未包含任何主题,则应自动应用这些主题,即当“DialogButtonStyle”等键未定义并导致输出中出现错误消息时。
我想要实现的是我的 UI 库是完全可主题化的,但也可以在无需关心自定义主题的情况下使用。
我尝试了什么:
(1) 定义一个包含后备样式的 dummy App.xaml。这在设计时(设计器预览、代码完成)有效,但在运行时无效。
(2) 在“Themes/Generic.xaml”中定义样式。这似乎只适用于隐式样式,不适用于显式样式。
(3) 将 Generic.xaml 合并到所有使用该样式的 XAML 文件的资源中。这不起作用,因为样式现在会覆盖主题。
【问题讨论】: