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的做用。不由感慨在項目中直接根據源代碼摸索真不如好好看一本書呀。繼承

相關文章
相關標籤/搜索