如何在第一次读取DependencyProperty时执行代码
本文关键字:执行 代码 DependencyProperty 读取 第一次 | 更新日期: 2023-09-27 18:01:44
我想为DependencyProperty
创建一些类似于后期绑定的东西。我有一个带图标的ListView
。我希望图标加载只有当他们实际上需要/显示。显示图标元素时,调用IconProperty
上的GetValue
,但只能返回默认值(即null
)。我想注入代码加载相关图标时,初始值是null
。
我的第一种方法是为属性创建自定义getter/setter,而不使用DependencyProperty
。它工作,但我想知道它是否是最佳的。
当我使用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;
}
// ...
}
考虑上面的代码:如何在第一个GetValue()
出现之前调用GetIcon()
?
不要使用依赖属性。
一个普通的CLR属性(带有可选的INotifyPropertyChanged
实现)就足够了:
public class DisplayItem : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private ImageSource icon;
public ImageSource Icon
{
get
{
if (icon == null)
{
icon = ... // load here
}
return icon;
}
private set
{
icon = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Icon"));
}
}
}
为什么要知道依赖属性值何时被访问?如果绑定到视图中的某个属性,则该属性将在初始加载组件时被访问。因此,您可以在Loaded
上调用GetIcon()
。如果使用MVVM,只需将Loaded事件绑定到某个命令,否则只需处理事件并调用函数。
如果您打算移动到MVVM模式,只需使用CLR属性作为另一个答案建议,将做的技巧