簡體   English   中英

首次讀取DependencyProperty時如何執行代碼?

[英]How to execute code when a DependencyProperty is first read?

我想為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屬性(如其他答案所示)就可以解決問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM