我有一个名为TemplateButton的自定义UserControl
。我尝试了很多方法将PropertyMetadata
设置为LinearGradientBrush
,但似乎没有任何帮助。那么有什么解决方案吗?
public LinearGradientBrush myProperty
{
get { return (LinearGradientBrush)GetValue(myPropertyProperty); }
set { SetValue(myPropertyProperty, value); }
}
// Using a DependencyProperty as the backing store for myProperty. This enables animation, styling, binding, etc...
public static readonly DependencyProperty myPropertyProperty =
DependencyProperty.Register("myProperty", typeof(LinearGradientBrush), typeof(TemplateButton), new PropertyMetadata(0));
或者只是
new PropertyMetadata(0));
我需要使用什么来代替0
?
任何可变引用类型依赖属性的默认值都应该是null
。
否则,拥有类的多个实例可能会对同一个默认值对象进行操作,这可能会导致意外行为。
public static readonly DependencyProperty myPropertyProperty =
DependencyProperty.Register(
nameof(myProperty),
typeof(LinearGradientBrush),
typeof(TemplateButton),
new PropertyMetadata(null));
理想情况下,除非您真的需要,否则根本不要设置任何PropertyMetadata:
public static readonly DependencyProperty myPropertyProperty =
DependencyProperty.Register(
nameof(myProperty),
typeof(LinearGradientBrush),
typeof(TemplateButton));