我有一个从UserControl
派生的控件PaneBase
。没有XAML,它只是一个控件。有问题的UserControl
类型是来自Catel的类型,但我在使用System.Windows.Controls.UserControl
时仍然观察到了这个问题。
public class PaneBase : UserControl
{
public static readonly DependencyProperty TitleProperty =
DependencyProperty.Register("Title",
typeof(string),
typeof(PaneBase),
new PropertyMetadata(default(string)));
public string Title
{
get => (string) GetValue(TitleProperty);
set => SetValue(TitleProperty, value);
}
}
我有另一个从PaneBase
派生的控件EquationPane
,它确实有XAML:
EquationPane.xaml
<local:PaneBase x:Class="EngineersToolkit.Windows.Views.Panes.EquationPane"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:catel="http://schemas.catelproject.com" xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:EngineersToolkit.Windows.Views.Panes"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="Equation"
d:DataContext="{d:DesignData EquationPaneViewModel}" d:DesignHeight="450" d:DesignWidth="800"
mc:Ignorable="d">
<Grid>
<TextBox Width="150" Height="30"
Text="{Binding Equation, Mode=TwoWay}" />
</Grid>
</local:PaneBase>
EquationPane.xaml.cs
public partial class EquationPane
{
public EquationPane()
{
InitializeComponent();
DataContext = new EquationPaneViewModel();
}
}
到目前为止,所有这些都是有效的,当我在窗口中包含一个EquationPane
时,它就会正常显示:
<Grid>
<panes:EquationPane Width="100" Height="100"
HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
Background="Aqua" />
</Grid>
如果我尝试设置控件的样式,它仍然可以正常工作:
<Style TargetType="{x:Type panes:EquationPane}">
<Setter Property="Background" Value="Red" />
</Style>
然而,如果我将样式改为PaneBase
,事情就开始崩溃了。如果我将TargetType
更改为PaneBase,则根本不会应用该样式。但是,如果我覆盖PaneBase
中的依赖属性元数据,如下所示:
static PaneBase()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(PaneBase),
new FrameworkPropertyMetadata(
typeof(PaneBase)));
}
然后该控件将完全停止呈现,留下一个空白窗口。为什么会发生这种情况?
发布于 2018-05-31 14:58:21
隐式样式不会自动应用于派生类型。要将PaneBase样式应用于EquationPane,可以执行以下操作之一:
1.把这个写到你的EquationPane.xaml.cs上
public EquationPane()
{
this.SetResourceReference(StyleProperty, typeof(PaneBase));
}
2.显式提供使用EquationPane的样式
<panes:EquationPane Style="{DynamicResource {x:Type PaneBase}}"/>
3.定义基于父样式的样式
<Style x:Key="{x:Type PaneBase}" TargetType="{x:Type PaneBase}">
<Setter Property="Background" Value="Red" />
</Style>
<Style TargetType="{x:Type panes:EquationPane}" BasedOn="{StaticResource {x:Type PaneBase}}"/>
https://stackoverflow.com/questions/50616792
复制相似问题