[英]AOP w/ PostSharp - Classic NotifyPropertyChanged PropertyChanged Event Handler Missing?
[英]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.