2016-02-26 55 views
0

我有一个自定义的控制的控制库:如何使自定义控件自动应用资源字典中定义的样式?

public class GlassButton : Button { 
} 

,我还定义了一个资源字典样式的控制:

<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> 

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

我该如何做到这一点? (我很好地对我的控制背后的代码进行更改)。

回答

1

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

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文件改变生成操作属性页之前的默认样式会得到正确应用于我的控制。

+0

这是对的,是的;尽管我真的希望避免将XAML从CS文件中分离出来......也许有一种方法,但这绝对是我以前做过的。谢谢。 – Will

0

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

所以,你可以删除当前的风格,并添加新的样式动态象下面这样:enter image description here

相关问题