簡體   English   中英

從抽象類繼承靜態事件的 INotifyPropertyChanged

[英]Inherit INotifyPropertyChanged for Static Event from abstract Class

我正在嘗試為各種硬件實現多個抽象層,我發現我已經實現了大約 5 次相同的功能, NofityStaticPropertyChanged (來自此處)。

    /// <summary>
    /// A slightly different implementation of Static Property Changed, from here:
    /// https://stackoverflow.com/a/42111290/2444435
    /// </summary>
    public static event PropertyChangedEventHandler StaticPropertyChanged;

    protected static void NotifyStaticPropertyChanged(string propertyName)
    {
        StaticPropertyChanged?.Invoke(null, new PropertyChangedEventArgs(propertyName));
    }

我想讓所有這些類都繼承自abstract class AbstractionBase以避免重用代碼。

我在別處讀過關於如何為非靜態成員繼承這種函數的文章,但我從來沒有真正實例化這些抽象層/工廠。

我不確定這實際上是否可行,因為不能繼承靜態屬性。 我覺得它應該是,因為它基本上是一個函數,而不是一個屬性? 我目前的嘗試是這樣的:

public abstract class AbstractionBase : INotifyPropertyChanged
{
    //THIS IS NOT WORKING!
    #region INofity Declarations
    /// <summary>
    /// A slightly different implementation of Static Property Changed, from here:
    /// https://stackoverflow.com/a/42111290/2444435
    /// </summary>
    public static event PropertyChangedEventHandler StaticPropertyChanged;

    protected static void NotifyStaticPropertyChanged(string propertyName)
    {
        StaticPropertyChanged?.Invoke(null, new PropertyChangedEventArgs(propertyName));
    }

    #endregion
} 

謝謝! 我有一種感覺,我可能無法擺脫這種重復數據刪除嘗試,但如果可能的話,那就太好了!

WPF 4.5 支持綁定到靜態屬性,您所要做的就是創建一個同名的靜態事件處理程序,並附加文本“Changed”,然后調用它而不是您的 StaticPropertyChanged:

public class MyStaticClass
{
    public static event EventHandler MyStaticPropertyChanged;

    private static string _MyStaticProperty = "Hello World!";
    public static string MyStaticProperty
    {
        get { return _MyStaticProperty; }
        set
        {
            if (_MyStaticProperty != value)
            {
                _MyStaticProperty = value;
                MyStaticPropertyChanged?.Invoke(null, EventArgs.Empty);
            }
        }
    }
}

你會像這樣綁定:

<TextBlock Text="{Binding Path=(vm:MyStaticClass.MyStaticProperty), Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" />

老實說,這對我來說更像是一個架構問題。 如果您正在使用依賴注入框架……並且您應該……那么絕對不需要為任何東西使用靜態屬性,只需將它們放在它們自己的類中並設置您的 DI 使其成為單例。

暫無
暫無

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

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