这是一个简单的自定义控件,用于说明我的问题。
如您所见,它有一个名为
这是我在
正如您所看到的,我在
那么您认为边框背景会设置成什么颜色?红色还是蓝色?
答案都不是。
如果我在控件的某个应该可用此值的位置(例如
样式中设置该值也没有任何作用(它不会根据我的样式setter delaration设置为蓝色)。这表明,对于
然而,这个可以工作。
public sealed class TestControl : Control
{
public static DependencyProperty TestColorProperty = DependencyProperty.Register("TestColor", typeof(Brush), typeof(TestControl), new PropertyMetadata(new SolidColorBrush(Colors.Blue)));
public Brush TestColor
{
get { return (Brush)GetValue(TestColorProperty); }
set { SetValue(TestColorProperty, value); }
}
public TestControl()
{
this.DefaultStyleKey = typeof(TestControl);
}
}
如您所见,它有一个名为
Brush
的依赖属性,其默认值为Blue
(如上所示,在PropertyMetaData
中设置)。这是我在
Generic.xaml
中控件的XAML代码。<Style TargetType="local:TestControl">
<Setter Property="TestColor" Value="Red" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:TestControl">
<Border
Background="{TemplateBinding TestColor}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<TextBlock Text="TEST" />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
正如您所看到的,我在
Style
中设置了TestColor
Brush依赖属性为红色,覆盖了默认值蓝色,如我在PropertyMetaData中声明的。请注意,我的模板中的边框使用TemplateBinding
将背景设置为讨论中的刷子。那么您认为边框背景会设置成什么颜色?红色还是蓝色?
答案都不是。
如果我在控件的某个应该可用此值的位置(例如
OnApplyTemplate
)中设置断点,则该值为null,而不是预期的默认值红色。实际上,我已经在控件的所有生命周期点设置了断点,并且从未使用ProprtyMetaData中的默认值。样式中设置该值也没有任何作用(它不会根据我的样式setter delaration设置为蓝色)。这表明,对于
SolidColorBrush
,样式setter出现了问题。然而,这个可以工作。
public BlankPage()
{
this.InitializeComponent();
testcont.TestColor = new SolidColorBrush(Colors.Orange);
}
这也可以正常工作:
<Grid Background="{StaticResource ApplicationPageBackgroundBrush}">
<local:TestControl TestColor="Green" />
</Grid>
但是TemplateBinding
根本不起作用,这很重要,因为我正在尝试编写可重复使用的自定义控件。
这是一个 bug 吗?
迪恩