如何为从dependencyobject派生的类型的依赖属性设置默认值 [英] How can i set a default value for a dependency property of type derived from dependencyobject

查看:25
本文介绍了如何为从dependencyobject派生的类型的依赖属性设置默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 WPF 的新手,这是我的第一篇文章.我创建了一个名为Fruit"的类,它继承自DependencyObject"并添加了一个名为Apple"的额外属性.我创建了一个新的自定义控件,其中包含一个名为MyFruit"的Fruit"类型的依赖属性.我的问题是,如何为MyFruit"对象(即Apple"属性?我想使用该对象在 XAML 中设置它)中的属性设置默认值.

I am new to WPF and this is my first post. I have created a class called 'Fruit' that descends from 'DependencyObject' and adds and extra property called 'Apple'. I have created a new custom control that includes a Dependency Property called 'MyFruit' of type 'Fruit'. My question is, how can i set the default value for the properties within 'MyFruit' object (i.e. the 'Apple' property? I would like to set this in XAML using the object.

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

Instead of null in your dependency property metadata insert

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

这篇关于如何为从dependencyobject派生的类型的依赖属性设置默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆