ClassLibary和WPF User Control LIbary和WPF Custom Control Libary的异同

  说来惭愧,接触WPF这么长时间了,今天在写自定义控件时遇到一个问题:运行界面中并无显示自定义控件,经调试发现原来没有加载Themes中的Generic.xaml。app

但是为何在其余solution中能够成功显示呢?后来就google学习了一下WPF中加载资源的相关文档,但都是理论性的介绍。对这个问题仍是没有多大的帮助。ide

没有办法只能比较两个solution中的proj有什么不一样,打开proj属性,发现application、build、buildEvents...等都同样,后来只能比较assemblyInfo,发现多了学习

[assembly:ThemeInfo(
......
......
......
)]

一瞬间像找到了答案同样兴奋(虽然没有验证),继续万能的google呀,因而找到了ClassLiary,WPF User Control Libary,WPF Custom Control Libary.ui

1:先看Class Library和WPF User Control Library,区别在于,google

  • 增长了4个Reference,PresentationCore,PresentationFramework,System.Xaml,WindowsBase
  • AssemblyInfo.cs中多了ThemeInfo的Attribute,以下,
    [assembly:ThemeInfo(
        ResourceDictionaryLocation.None,
        //where theme specific resource dictionaries are located
        //(used if a resource is not found in the page,
        // or application resource dictionaries)
        ResourceDictionaryLocation.SourceAssembly
        //where the generic resource dictionary is located
        //(used if a resource is not found in the page,
        // app, or any theme specific resource dictionaries)
    )


因此若是要在一个Class Library中新建一个WPF UserControl就须要新建一个WPF UserControl,Visual Stuido会自动为你加入4个Reference,而后手动在AssemblyInfo.cs加入ThemeInfo便可.spa

[assembly: ThemeInfo(ResourceDictionaryLocation.None,
                     ResourceDictionaryLocation.SourceAssembly)]

  

2:而后说说WPF User Control Library和WPF Custom Control Library的区别,结果看下来基本没区别,无非是Custom Control Library默认帮你建立了一个CustomControl继承Control,而后在Themes目录下建立了Generic.xaml。调试

因此若是新建Class Library后须要建立Custom Control,就须要增长对应的4个Renference,在Add File中没法增长Custom Control,这个VS有点2,只能手动建立Class,而后改成继承自Control,orm

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

而后建立目录Themes增长Generic.xaml,肯定Generic.xaml的build方式为Page,最后增长ThemeInfo便可。blog

 

3:总结一下,原来真的就是assembly中的assembly:ThemeInfo那段代码起到了加载ResourceDictionary的做用。不由感慨在项目中直接根据源代码摸索真不如好好看一本书呀。继承

相关文章
相关标签/搜索