C# 如何为从dependencyobject派生的类型的dependency属性设置默认值

C# 如何为从dependencyobject派生的类型的dependency属性设置默认值,c#,wpf,xaml,C#,Wpf,Xaml,我是WPF的新手,这是我的第一篇帖子。我创建了一个名为“Fruit”的类,它是从“DependencyObject”派生而来的,并添加了一个名为“Apple”的额外属性。我创建了一个新的自定义控件,其中包含一个名为“MyFruit”的类型为“Fruit”的依赖属性。我的问题是,如何设置“MyFruit”对象中属性(即“Apple”属性)的默认值?我想使用该对象在XAML中进行设置 public class Gauge : Control { . . . //--

我是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"));

您需要像这样使用属性元数据

class MyValidation
{ 

    public bool status
        {
            get { return (bool)GetValue(statusProperty); }
            set { SetValue(statusProperty, value); }
        }

        public static readonly DependencyProperty statusProperty =
            DependencyProperty.Register("status", typeof(bool), typeof(MyValidation),new PropertyMetadata(false));

}

感谢您的回复,但我想知道如果可能,如何使用setter在XAML中设置“Apple”属性?“您的默认值在这里”这到底是如何工作的?Metadate默认值必须是值类型。但我需要为引用类型的“Fruit”类中的子属性设置默认值?是的,你是对的…你可以通过TargetNullValue属性定义默认值。谢谢,我必须尝试“TargetNullValue”。但我认为我找到了另一个解决方案。如果我创建了一个资源,然后以我的风格使用setter。这个解决方案对我很有效。如果未来的读者登陆这里,请查看Rick的答案。如果没有它,我的头发就会少一些。