如何使自定义控件自动应用资源字典中定义的样式?

时间:2016-02-26 17:45:11

标签: c# wpf xaml templates resourcedictionary

我有一个带有自定义控件的控件库:

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:Animations="clr-namespace:WPFTools.Classes"
    xmlns:Controls="clr-namespace:WPFTools.Controls"
    xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
    xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
    mc:Ignorable="d">
    <Style TargetType="{x:Type Controls:GlassButton}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">

我还定义了一个资源字典来设置控件的样式:

GlassButton

我希望能够将<Window.Resources> <ResourceDictionary Source="Foo"/> </Window.Resources> 拖放到窗口或控件上, NOT 必须执行此操作:

for (var key in post) {
    var one = post[key];
    console.log(one);    
}

我之前能够做到这一点,但这些知识似乎已经丢失了。

我怎样才能实现这一目标? (我很好地改变了我的控制背后的代码。)

2 个答案:

答案 0 :(得分:1)

我不得不重新记住一周前它是如何工作的,这是我必须要做的才能让它适合我。自定义控件的典型方法是在名为generic.xaml的文件中定义样式,该文件位于项目根目录正下方的Themes文件夹中。然后,您需要覆盖自定义控件类的静态构造函数中的默认样式。它看起来像这样:

public class GlassButton : Button
{
    static GlassButton()
    {
        DefaultStyleKeyProperty.OverrideMetadata( typeof( GlassButton ),
            new FrameworkPropertyMetadata( typeof( GlassButton ) ) );
    }
}

最后,您需要设置适当的程序集属性,以表明您的通用主题位于程序集中。这样的内容会出现在Properties\AssemblyInfo.cs文件中:

using System.Windows;
[assembly:ThemeInfo( ResourceDictionaryLocation.None,
    ResourceDictionaryLocation.SourceAssembly )]

我不确定这是否是绝对必要的,但我还必须将generic.xaml文件中的Build Action属性更改为Page,然后才能将默认样式正确应用于我的控件。

答案 1 :(得分:0)

这项工作的最佳实践是创建DictionaryResources在应用程序中包含您想要的每种应用程序样式的所有WPF样式。 enter image description here

因此,您可以移除当前样式并动态添加新样式,如下所示:enter image description here