我创建了一个类库程序集,在其中创建了自定义控件,并在generic.xaml文件中定义了默认样式。
似乎这是一个很常见的问题,只要很多人都在发帖。然而,我无法为我的案子找到任何有用的答案。
在测试应用程序中,如果手动将自定义控件程序集中的generic.xaml文件合并到应用程序App.xaml文件中,如下所示:
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/MyControlsAssembly;component/Themes/generic.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>然后,自定义控件正确地以主题为主题,但如果我不手动合并generic.xaml,则这些控件将以默认的Windows主题出现。
你能告诉我我忘记和/或做错了什么吗?
更多信息:
[assembly: ThemeInfo(ResourceDictionaryLocation.SourceAssembly, ResourceDictionaryLocation.SourceAssembly)]
(注意:对于ThemeInfo属性的任何参数组合,结果都是一样的)发布于 2016-01-17 00:04:01
为了在我的自定义控件库中应用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("...")]发布于 2013-09-01 18:26:21
您需要在自定义控件构造函数中使用以下行:
public class MyCustomControl : Control
{
static MyCustomControl()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(MyCustomControl), new FrameworkPropertyMetadata(typeof(MyCustomControl)));
}
}然后,如果主题文件夹中有一个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>现在,样式将自动应用,而不需要任何额外的合并。
发布于 2022-01-26 14:41:32
在我的例子中,我忘记从x:Key标记中删除<Style>。
错误:
<Style TargetType="controls:IpTextBox" x:Key="MyControlStyle">更正:
<Style TargetType="controls:IpTextBox">https://stackoverflow.com/questions/11149167
复制相似问题