0
我有一個WPF應用程序與兩個viewmodels(AViewModel
,BViewModel
)。 我認爲主要問題是Singleton.Instance.Handle.Add("...",(m)=>{...});
無法從模型中刪除,因爲它具有高耦合。而當我想更新收集我需要過去Singleton.Instance.Handle.Add("...",(m)=>{...});
如何在沒有粘貼每次Singleton.Instance.Handle.Add("...",(m)=>{...});
wpf用事件替換字典
public class AViewModel
{
AModel A = new AModel();
}
和BViewModel
更新集合每次:
public class BViewModel
{
BModel B = new BModel();
}
AModel
:
public class AModel
{
public ObservableCollection<DataType> AItems { get; set; }
public AModel()
{
AItems = new ObservableCollection<DataType>();
UpdateAModel();
}
public void UpdateAModel()
{
// Problem with High Coupling, can not remove into another class
Singleton.Instance.Handle.Add("MessageB", (m) =>
{
Dictionary<string, DataType> d = m.Message.Json.GetFirstArgAs<Dictionary<string, DataType>>();
foreach (KeyValuePair<string, DataType> item in d)
{
// Update AItems
}
// Many strings of code
// Update AItems, problem with add or remove items in ObservableCollection because AItems on UI Thread
});
}
}
BModel
:
public class BModel
{
public ObservableCollection<DataType> BItems { get; set; }
public BModel()
{
BItems = new ObservableCollection<DataType>();
UpdateBModel();
}
public void UpdateBModel()
{
// Problem with High Coupling, can not remove into another class
Singleton.Instance.Handle.Add("MessageA", (m) =>
{
Dictionary<string, DataType> d = m.Message.Json.GetFirstArgAs<Dictionary<string, DataType>>();
foreach (KeyValuePair<string,DataType> item in d)
{
// Update BItems
}
// Many strings of code
// Update BItems, problem with add or remove items in ObservableCollection because AItems on UI Thread
});
}
}
這兩個模型都包含ObservableList
,它用來自web的數據進行更新。
public class Singleton
{
private static Singleton instance;
public Dictionary<string, Action<MessageEventArgs>> Handle { get; set; }
private Singleton()
{
Handle = new Dictionary<string, Action<MessageEventArgs>>();
socket = new Client(UrlSocketServer);
socket.Message += Message;
}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
private void Message(object sender, MessageEventArgs e)
{
if (Handle.ContainsKey(e.Message.Event))
{
Handle[e.Message.Event](e);
}
}
}