簡體   English   中英

NotifyPropertyChanged未觸發事件[PostSharp]

[英]NotifyPropertyChanged not firing event [PostSharp]

我是PostSharp的新手(剛剛獲得了許可證),我一直在嘗試在自己的應用程序中使用它。 我有以下設置類:

[NotifyPropertyChanged]
public class Consts
{
    public string test2 {get; set;} = "foobar";

    public string test
    {
        get { return GetValue("test"); }
        set { UpdateSetting(nameof(test), value.ToString(CultureInfo.InvariantCulture)); }
    }

    [Pure]
    public static string GetValue(string s) => ConfigurationManager.AppSettings[nameof(s)];

    [Pure]
    private static void UpdateSetting(string key, string value)
    {
        var cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

        cfg.AppSettings.Settings[key].Value = value;
        cfg.Save(ConfigurationSaveMode.Modified);

        ConfigurationManager.RefreshSection("appSettings");
    }
}

然后在我的訂戶類上:

var cst = new Consts();
Post.Cast<Consts, INotifyPropertyChanged>(cst).PropertyChanged +=
                (o, args) => Debug.Write("PropertyChanged fired");
cst.test = "test test"; // Gives no result
cst.test2 = "test test"; // Event firing correctly

當我在我的getters和setters方法中使用方法時,該事件不會觸發,盡管標記為純方法,但當它是一個簡單屬性時,效果很好。

我花了最后一天搜尋Google的答案,但沒有運氣。 沒有線程可以解決我的問題。

我想念什么?

[NotifyPropertyChanged]方面檢測到對類字段的更改,然后根據檢測到的依賴項(屬性值取決於該特定字段)觸發適當的事件。

在您的情況下,這恰恰是test2屬性的作用,以及aspect對該屬性起作用的原因。

另一方面, test屬性無法自動運行。 該屬性的值取決於ConfigurationManager.AppSettings.Item 第一個問題是AppSettings是靜態屬性,即無法檢測到對其的更改。 如果假定它永遠不會更改,那么第二個問題是NameValueCollection沒有實現INotifyPropertyChanged ,這意味着無法知道該值實際上已更改。

您沒有收到任何警告,因為您已將這兩種方法都標記為“ Pure ,這在通常的意義上都不是。 GetValue使用全局可變狀態。 SetValue更改全局可變狀態。

由於無法掛鈎到AppSettings來接收對集合的更改,因此在設置屬性后,您需要引發更改的通知。 這可以通過調用NotifyPropertyChangedServices.SignalPropertyChanged方法來完成。 您的代碼將如下所示:

[NotifyPropertyChanged]
public class Consts
{
    public string test2 { get; set; } = "foobar";

    public string test
    {
        get { return GetValue("test"); }
        set { UpdateSetting(nameof(test), value.ToString(CultureInfo.InvariantCulture)); }
    }

    [SafeForDependencyAnalysis]
    public string GetValue(string s) => ConfigurationManager.AppSettings[nameof(s)];

    private void UpdateSetting(string key, string value)
    {
        var cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

        cfg.AppSettings.Settings[key].Value = value;
        cfg.Save(ConfigurationSaveMode.Modified);

        ConfigurationManager.RefreshSection("appSettings");
        NotifyPropertyChangedServices.SignalPropertyChanged(this, key);
    }
}

請注意,如果存在Consts類的多個實例,則它們將不會共享更改,因此無法通過ConfigurationManaged傳遞該信息。

暫無
暫無

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

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