我是 WPF 的新手,这是我的第一篇文章。我创建了一个名为“Fruit”的类,它派生自“DependencyObject”并添加了名为“Apple”的额外属性。我创建了一个新的自定义控件,其中包含一个名为“MyFruit”且类型为“Fruit”的依赖属性。我的问题是,如何为“MyFruit”对象(即“Apple”属性)中的属性设置默认值?我想使用该对象在 XAML 中进行设置。
public class Gauge : Control
{
.
.
.
//---------------------------------------------------------------------
#region MyFruit Dependency Property
public Fruit MyFruit
{
get { return (Fruit)GetValue(MyFruitProperty); }
set { SetValue(MyFruitProperty, value); }
}
public static readonly DependencyProperty MyFruitProperty =
DependencyProperty.Register("MyFruit", typeof(Fruit), typeof(CircularGauge), null);
#endregion
}
//-------------------------------------------------------------------------
#region Fruit class
public class Fruit : DependencyObject
{
private int apple;
public int Apple
{
get { return apple; }
set { apple = value; }
}
}
#endregion
最佳答案
在您的依赖属性元数据插入中代替 null
new UIPropertyMetadata("YOUR DEFAULT VALUE GOES HERE")
现在变成了
public static readonly DependencyProperty MyFruitProperty =
DependencyProperty.Register("MyFruit", typeof(Fruit), typeof(CircularGauge), new UIPropertyMetadata("YOUR DEFAULT VALUE GOES HERE"));
关于c# - 如何为从 dependencyobject 派生的类型的依赖属性设置默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6729568/