【问题标题】:How can i set a default value for a dependency property of type derived from dependencyobject如何为从dependencyobject派生的类型的依赖属性设置默认值
【发布时间】:2011-07-18 07:02:23
【问题描述】:

我是 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

【问题讨论】:

    标签: c# wpf xaml


    【解决方案1】:

    在你的依赖属性元数据中插入而不是 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"));
    

    【讨论】:

    • 感谢您的回复,但我想知道如果可能的话,如何使用 setter 在 XAML 中设置“Apple”属性?
    • "你的默认值在这里" 这究竟是如何工作的? Metadate 默认值必须是值类型。但是我需要为“水果”类中的子属性设置一个默认值,这是一个引用类型?
    • 是的,您是对的...您可以通过 TargetNullValue 属性定义默认值。
    • 谢谢,我必须尝试“TargetNullValue”。但我认为我找到了另一种解决方案。如果我创建一个资源 然后按照我的风格我可以使用 setter。 这个解决方案对我有用
    • 对于登陆这里的未来读者,请查看 Rick 在this related post 中的回答。如果没有它,我头上的头发会更少。
    【解决方案2】:

    你需要像这样使用PropertyMetaData

    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));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-23
      • 2013-01-05
      • 2011-08-19
      • 1970-01-01
      • 2011-12-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多