首次读取DependencyProperty时如何执行代码?

时间:2016-08-10 08:46:55

标签: c# wpf

我想为DependencyProperty创建类似后期绑定的内容。 我有ListView图标。我想只在实际需要/显示图标时才加载图标。显示图标元素时,GetValue上会调用IconProperty,但它只能返回默认值(null)。我希望在初始值为null时注入代码以加载相关图标。

我的第一种方法是在不使用DependencyProperty的情况下为属性创建自定义getter / setter。它有效,但我不知道它是否是最佳的。

当我使用DependencyProperty时,我可以轻松确定何时通过OnPropertyChanged覆盖进行更改。我不知道何时应该为getter注入初始化。

public class DisplayItem : DependencyObject {

    // ...

    public static readonly DependencyProperty IconProperty =
        DependencyProperty.Register(
            "Icon",
            typeof(ImageSource),
            typeof(DisplayItem),
            null
        );

    public ImageSource Icon {
        get { return (ImageSource)GetValue(IconProperty); }
        private set { SetValue(IconProperty, value); }
    }

    private void GetIcon() {
        // Some code to actually fetch the icon image...
        // ...
        Icon = loadedImageSource;
    }

    // ...

}

考虑上面的代码:如何在第一个GetIcon()出现之前准确调用GetValue()

2 个答案:

答案 0 :(得分:1)

不要使用依赖属性。

普通的CLR属性(带有可选的 Column Row 1 2 3 4 1 (255, 0,0) (255, 0,0) (255, 0,0) (255, 0,0) 2 (255, 0,0) (255, 0,0) (255, 0,0) (255, 0,0) 3 ( 0, 0,0) ( 0, 0,0) ( 0, 0,0) ( 0, 0,0) 4 ( 0,255,0) ( 0,255,0) ( 0,255,0) ( 0,255,0) 实现)就足够了:

INotifyPropertyChanged

答案 1 :(得分:1)

为什么要知道何时访问依赖项属性值? 如果绑定到视图中的某个属性,则在最初加载组件时将访问该属性。因此,您可以在GetIcon()时拨打Loaded。如果您正在使用MVVM,只需将Loaded事件绑定到某个命令,否则只需处理该事件并调用该函数。

如果您计划转向MVVM模式,只需使用CLR属性作为另一个答案建议,就可以了。