首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

WPF 自定義控件庫輸出 DLL 缺少主題資源:Generic.xaml 統一定義與 DefaultStyleKey 註冊

     編輯:程式設計綜合問答

現象:WPF 類庫輸出 DLL,引用專項中自定義控件樣式不生效,Themes/Generic.xaml 未被打包/讀取。

根因

WPF 查找控件默認樣式流程:

  1. 控件靜態構造函數調用 DefaultStyleKeyProperty.OverrideMetadata。
  2. 運行時按 DefaultStyleKey 類型尋找 Themes/Generic.xaml 中對應 Style。
  3. 若 Generic.xaml 未嵌入資源、或 Build Action 非 Resource,則找不到。

修正步驟

  1. 確保 Themes/Generic.xaml 存在,屬性:
    Build Action = Resource(非 Embedded Resource)。
  2. 控件類靜態構造函數註冊:
    static MyControl() { DefaultStyleKeyProperty.OverrideMetadata(typeof(MyControl), new FrameworkPropertyMetadata(typeof(MyControl))); }
  3. Generic.xaml 中定義:
    <Style TargetType="{x:Type local:MyControl}"> ... </Style>

副作用與規避

註冊後,**無法在外部顯式引用 Generic.xaml 中的 Style**(如 Style={StaticResource MyStyle})。
規避:將可複用樣式單獨放入 Styles/Shared.xaml,ResourceDictionary.MergedDictionaries 合併引用。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved