簡體   English   中英

如何為從dependencyobject派生的類型的依賴屬性設置默認值

[英]How can i set a default value for a dependency property of type derived from dependencyobject

我是 WPF 的新手,這是我的第一篇文章。 我創建了一個名為“Fruit”的 class,它源自“DependencyObject”,並添加了一個名為“Apple”的額外屬性。 我創建了一個新的自定義控件,其中包含一個名為“MyFruit”的“Fruit”類型的依賴屬性。 我的問題是,如何設置“MyFruit”object(即“Apple”屬性)中屬性的默認值?我想使用 object 在 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));

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM