【问题标题】:Apply themes to wpf and use styles将主题应用于 wpf 并使用样式
【发布时间】:2011-12-13 08:06:38
【问题描述】:

我正在尝试将主题应用于一堆 wpf 项目。有一个程序集包含 generic.xaml 和不同的应用程序。据我了解,我不能将 ThemeInfo 属性与 ResourceDictionaryLocation.ExternalLocation 一起使用,因为名称必须与我的程序相同,但我有多个程序...

所以我搜索并发现我只需要将字典作为 MergedDictionary 包含在 app.xaml 中

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/ClassLibrary1;component/Themes/generic.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

这基本上有效。但是,如果我对控件使用样式,它将不再应用 generic.xaml 样式:

ClassLibrary1.dll 中的generic.xaml

<ResourceDictionary x:Class="ClassLibrary1.Themes.generic"
                xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

<Style TargetType="{x:Type Button}">
    <Setter Property="Background"
            Value="Black" />
</Style>

程序中的窗口

<Window x:Class="Theming.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">

    <Window.Resources>
        <Style TargetType="Button"
               x:Key="ButtonGreenTextStyle">
            <Setter Property="Foreground"
                    Value="Green" />
        </Style>
    </Window.Resources>

    <Grid>
        <Button Style="{DynamicResource ButtonGreenTextStyle}" Content="Test" />
    </Grid>
</Window>

我必须做的是,WPF 会将我的 generic.xaml 中的样式理解为所有按钮的基本样式(我知道我还必须编写一个 ControlTemplate;上面的代码只是为了简单起见)

【问题讨论】:

    标签: wpf styles themes styling


    【解决方案1】:

    我会尝试两件事

    • 创建一个通用的ButtonBase 样式/模板来设置所有的外观 按钮
    • 尝试在 ButtonGreeTextStyle 上使用 BasedOn 属性, 基于现有样式。

    【讨论】:

    • 据我所知 WPF 不会为 BaseClasses 应用模板。 BasedOn 可以工作,但我想知道 WPF 是否不应该将 Style 应用为默认值,因为它是在 generic.xaml 中定义的
    【解决方案2】:

    我找到了另一个解决方案。您必须根据自定义标记编写样式:

    这将应用当前的主题样式。这个 MarkupExtension 的代码可以在这里找到:

    How do I alter the default style of a button without WPF reverting from Aero to Classic?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-30
      • 1970-01-01
      • 1970-01-01
      • 2011-06-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多