首页 技术 正文
技术 2022年11月14日
0 收藏 431 点赞 4,925 浏览 1713 个字

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

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

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

[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,如下,
    [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即可.

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

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的作用。不禁感慨在项目中直接根据源代码摸索真不如好好看一本书呀。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,085
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,560
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,409
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,182
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,819
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,902