[英]Styles from generic.xaml are not applied
我制作了一個類庫程序集,在其中創建了自定義控件,並在 generic.xaml 文件中定義了默認樣式。
只要有很多人發布它,這似乎是一個很常見的問題。 但是我找不到任何有用的答案。
在我的測試應用程序中,如果我手動將自定義控件程序集中的 generic.xaml 文件合並到應用程序 App.xaml 文件中,如下所示:
那么自定義控件的主題是正確的,但如果我不手動合並 generic.xaml,這些控件將顯示為默認的 Windows 主題。
你能告訴我我忘記了什么和\/或做錯了什么嗎?
附加信息:
我的 ThemeInfo 程序集屬性定義如下:
(注意:對於 ThemeInfo 屬性的任意參數組合,結果都是一樣的)
Themes 文件夾中的 generic.xaml 文件旁邊還有另外兩個 .xaml 文件。
您需要在自定義控件構造函數中使用以下行:
public class MyCustomControl : Control
{
static MyCustomControl()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(MyCustomControl), new FrameworkPropertyMetadata(typeof(MyCustomControl)));
}
}
然后,如果在themes文件夾中有generic.xaml文件,則使用以下示例樣式:
<Style TargetType="{x:Type local:MyCustomControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:MyCustomControl}">
<Border>
<Label>Testing...</Label>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
現在風格將自動應用,無需任何額外的合並。
要在我的自定義控件庫中的Themes \\ Generic.xaml中應用默認樣式,我決定從一個完善的開源控件庫( MahApps )中尋找靈感。 該項目為您提供了一個如何構建和布局自定義控件庫的非常好的示例。
簡而言之,要在Themes \\ Generic.xaml中獲取默認樣式,您需要在自定義控件庫的AssemblyInfo.cs文件中包含以下內容:
[assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)]
在我的例子中,我的自定義控件AssemblyInfo.cs看起來像:
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Markup;
[assembly: AssemblyCopyright("...")]
[assembly: ComVisible(false)]
[assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0.0")]
[assembly: AssemblyTitleAttribute("...")]
[assembly: AssemblyDescriptionAttribute("")]
[assembly: AssemblyProductAttribute("...")]
[assembly: AssemblyCompany("...")]
不確定這是否適用於WPF,但它在Silverlight中適用於我:
構造函數:
public class MyCustomControl : Control
{
static MyCustomControl()
{
this.Style = (Style)Application.Current.Resources["MyCustomControlStyle"];
}
}
樣式:
<Style x:Key="MyCustomControlStyle" TargetType="{local:MyCustomControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{local:MyCustomControl}">
<Border>
<Label>Testing...</Label>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
由於自定義控件程序集中的以下屬性,我遇到了同樣的問題:
[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
將UltimateResourceFallbackLocation.Satellite
更改為UltimateResourceFallbackLocation.MainAssembly
或刪除第二個參數完全解決了我的問題(如果您不需要定義程序集的中性語言,也可以刪除該屬性)。
在我的情況下,我忘記從<Style>
標記中刪除x:Key
。
錯誤的:
<Style TargetType="controls:IpTextBox" x:Key="MyControlStyle">
正確的:
<Style TargetType="controls:IpTextBox">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.