我有一个自定义控件,它使用app.xaml中链接的资源字典中的样式。如果我删除链接并将链接添加到包含该控件的页面,它将不起作用。为什么会这样呢?为什么我的控件( dll)需要样式在app.xaml中,而不仅仅是在控件所在的页面上?
发布于 2012-06-15 23:59:31
为什么我的控件( dll)需要样式在app.xaml中,而不仅仅是在控件所在的页面上?
自定义控件需要默认样式。此默认样式是在构造函数中设置的。例如:
public CustomControl()
{
DefaultStyleKey = typeof(CustomControl);
}设置后,它将在包含此样式的程序集中进行查找。如果控件在应用程序中,则在App.xaml中查找。如果控件在类库中,则它在一个文件Generic.xaml中查找,该文件必须放在"Themes“文件夹中。您不需要将样式放置在这两个文件中。可以创建包含该样式的单独文件,并从App.xaml或Themes/Generic.xaml (基于定义控件的位置)引用该样式。为此,您需要在其中一个文件中创建一个MergedDictionary。如果您的控件是在应用程序中定义的,您将执行以下操作
<Application x:Class="MyApp.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<!--Application Resources-->
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Controls/CustomControl.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
<Application.Resources>
</Application>如果您的控件是在类库中定义的,主题/Generic.xaml应该如下所示
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/My.Custom.Assembly;component/FolderLocationOfXaml/CustomControl.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>无论您的自定义控件放在哪里,xaml看起来都是一样的
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:My.Custom.Assembly.Controls">
<Style TargetType="local:CustomControl">
<Setter Property="Background" Value="Transparent"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:CustomControl">
<Grid>
<! -- Other stuff here -->
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>如果未定义此默认样式,则无法确定要覆盖的样式。一旦定义了默认样式,您就可以在应用程序内或使用控件的任何其他地方更改样式。
发布于 2012-06-15 23:22:47
请尝试将样式移动到控件中,以验证控件使用字典中的项所需的所有引用是否都已就位。确保包含UserControl的项目引用了包含资源字典的项目。验证字典的源路径:
<ResourceDictionary Source="/AssemblyName;component/StylesFolderName/ResourceDictionaryName.xaml" />
https://stackoverflow.com/questions/11051750
复制相似问题