c# - 如何为从 dependencyobject 派生的类型的依赖属性设置默认值

标签 c# wpf xaml

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

相关文章:

c# - ListViewItem IsSelected Binding - 适用于 WPF,但不适用于 WinRT

c# - Entity Framework Linq何时查询Hints Sql数据库?

javascript - SignalR 集线器未连接

c# - 在 WPF MVVM 中更新 UI 时如何更改文本颜色

wpf - 如何将复选框与其内容对齐?

c# - 为什么 GetWindowRect 在我的 WPF 窗口中包含标题栏?

c# - 需要使用 Moq 进行单元测试以获取特定代码的帮助

c# - 在 Windows 2008 Server 上通过 TFS 进行 WatiN

.net - 如何在 ResourceDictionary 中存储 HTML 字符串?

c# - 我正在使用 try catch 但它仍然在 WPF 应用程序中引发错误