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

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

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

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

1
2
3
4
5
[assembly:ThemeInfo(
......
......
......
)]

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

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

  • 增加了4个Reference,PresentationCore,PresentationFramework,System.Xaml,WindowsBase
  • AssemblyInfo.cs中多了ThemeInfo的Attribute,如下,
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    [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即可.

1
2
[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,

1
2
3
4
5
public  class  Class1 : Control {
     static  Class1() {
         DefaultStyleKeyProperty.OverrideMetadata( typeof (Class1),  new  FrameworkPropertyMetadata( typeof (Class1)));
     }
}

然后创建目录Themes增加Generic.xaml,确定Generic.xaml的build方式为Page,最后增加ThemeInfo即可。

 

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

原文:http://www.cnblogs.com/jljxxf/p/3365563.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值