I have a WPF application with two viewmodels(AViewModel
,BViewModel
).
I think that main problem is that Singleton.Instance.Handle.Add("...",(m)=>{...});
cannot be removed from Model because it have High Coupling. And every time when i want to update collection i need to past Singleton.Instance.Handle.Add("...",(m)=>{...});
How to update collection without pasting every time Singleton.Instance.Handle.Add("...",(m)=>{...});
public class AViewModel
{
AModel A = new AModel();
}
and 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
});
}
}
Both models contain ObservableList
, which updates with data from 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);
}
}
}