Wpf从web向应用程序的不同部分提供数据
本文关键字:同部 提供数据 应用程序 web Wpf | 更新日期: 2023-09-27 18:10:46
我有一个从web服务器获取数据的WPF应用程序。
包含两个view
-
LeftView
-
RightView
-
LeftModel
-
RightModel
-
CentralModel
和两个ViewModels
-
LeftViewModel
-
RightViewModel
我将只显示LeftView
、LeftViewModel
、LeftModel
和CentralModel
(代码太多)。你可以在这里找到整个项目。
我猜主要问题是UpdateCollection()
与public ObservableCollection<SomeTypeA> Items {get; set;}
有高耦合。
因此我感觉我不能把UpdateCollection()
放在CentralModel
中。
我认为如果UpdateCollection()
将在CentralModel
中会更好,如何做到这一点?
工作逻辑非常简单,从web服务器传入的消息添加到public Dictionary<string, Action<MessageReceivedEventArgs>> Handle { get; set; }
public void Message(object sender, MessageReceivedEventArgs e)
{
var dresult = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, SomeTypeA>>(e.Message);
if (Handle.ContainsKey(dresult.Keys.ToList()[0]))
{
Handle[dresult.Keys.ToList()[0]](e);
}
}
,如果字典中包含键,则在模型
中触发事件CentralModel.Instance.Handle.Add("central_office", (m) =>
{
var dresult = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, SomeTypeA>>(m.Message);
Console.WriteLine(m.Message.ToString());
foreach (KeyValuePair<string,SomeTypeA> item in dresult)
{
if (!Items.Any(key=>key.ID==dresult["central_office"].ID))
{
Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => Items.Add(item.Value)));
}
foreach (SomeTypeA subitem in Items)
{
subitem.ID = item.Value.ID;
subitem.Name = item.Value.Name;
subitem.Value = item.Value.Value;
subitem.Work = item.Value.Work;
subitem.Department = item.Value.Department;
}
}
});
ServerClass.cs
namespace Server
{
class ServerClass
{
private WebSocketServer appServer;
public void Setup()
{
appServer = new WebSocketServer();
if (!appServer.Setup(2012)) //Setup with listening port
{
Console.WriteLine("Failed to setup!");
Console.ReadKey();
return;
}
appServer.NewMessageReceived += new SessionHandler<WebSocketSession, string>(appServer_NewMessageReceived);
Console.WriteLine();
}
public void Start()
{
if (!appServer.Start())
{
Console.WriteLine("Failed to start!");
Console.ReadKey();
return;
}
Console.WriteLine("The server started successfully! Press any key to see application options.");
SomeTypeA FirstWorker = new SomeTypeA()
{
Department = "Finance",
ID = "0",
Name = "John",
Work = "calculate money"
};
SomeTypeB SecondWorker = new SomeTypeB()
{
ID = "1",
Name = "Nick",
Work = "clean toilet"
};
while (true)
{
FirstWorker.value += 1;
SecondWorker.value += 5;
Dictionary<string, SomeTypeA> Element1 = new Dictionary<string, SomeTypeA>();
Element1.Add("central_office", FirstWorker);
Dictionary<string, SomeTypeB> Element2 = new Dictionary<string, SomeTypeB>();
Element2.Add("back_office", SecondWorker);
string message1 = Newtonsoft.Json.JsonConvert.SerializeObject(Element1);
string message2 = Newtonsoft.Json.JsonConvert.SerializeObject(Element2);
System.Threading.Thread.Sleep(2000);
foreach (WebSocketSession session in appServer.GetAllSessions())
{
session.Send(message1);
session.Send(message2);
}
}
}
private void appServer_NewMessageReceived(WebSocketSession session, string message)
{
Console.WriteLine("Client said: " + message);
session.Send("Server responded back: " + message);
}
}
}
Program.cs
namespace Server
{
class Program
{
static void Main(string[] args)
{
ServerClass myServer = new ServerClass();
myServer.Setup();
myServer.Start();
}
}
}
LeftView.cs
<Grid>
<ListView ItemsSource="{Binding LM.Items}">
<ListView.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Content="{Binding Name}"></Label>
<Label Grid.Column="1" Content="{Binding Work}"></Label>
<Label Grid.Column="2" Content="{Binding Value}"></Label>
<Label Grid.Column="3" Content="{Binding ID}"></Label>
<Label Grid.Column="4" Content="{Binding Department}"></Label>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
LeftViewModel.cs
namespace WpfApplication139.ViewModels
{
public class LeftViewModel
{
public LeftModel LM { get; set; }
public LeftViewModel()
{
LM = new LeftModel();
}
}
}
LeftModel.cs
namespace WpfApplication139.Models
{
public class LeftModel
{
public ObservableCollection<SomeTypeA> Items {get; set;}
public LeftModel()
{
Items = new ObservableCollection<SomeTypeA>();
CentralModel.Instance.Setup("ws://127.0.0.1:2012", "basic", WebSocketVersion.Rfc6455);
CentralModel.Instance.Start();
UpdateCollection();
}
public void UpdateCollection()
{
CentralModel.Instance.Handle.Add("central_office", (m) =>
{
var dresult = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, SomeTypeA>>(m.Message);
Console.WriteLine(m.Message.ToString());
foreach (KeyValuePair<string,SomeTypeA> item in dresult)
{
if (!Items.Any(key=>key.ID==dresult["central_office"].ID))
{
Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => Items.Add(item.Value)));
}
foreach (SomeTypeA subitem in Items)
{
subitem.ID = item.Value.ID;
subitem.Name = item.Value.Name;
subitem.Value = item.Value.Value;
subitem.Work = item.Value.Work;
subitem.Department = item.Value.Department;
}
}
});
}
}
}
CentralModel.cs
namespace WpfApplication139.Models
{
public class CentralModel
{
private WebSocket websocketClient;
private string url;
private string protocol;
private WebSocketVersion version;
private static CentralModel instance;
public Dictionary<string, Action<MessageReceivedEventArgs>> Handle { get; set; }
private CentralModel()
{
Handle = new Dictionary<string, Action<MessageReceivedEventArgs>>();
}
public void Setup(string url, string protocol, WebSocketVersion version)
{
this.url = url;
this.protocol = protocol;
this.version = WebSocketVersion.Rfc6455;
websocketClient = new WebSocket(this.url, this.protocol, this.version);
websocketClient.MessageReceived += new EventHandler<MessageReceivedEventArgs>(CentralModel.Instance.Message);
}
public void Start()
{
websocketClient.Open();
}
public static CentralModel Instance
{
get
{
if (instance == null)
{
instance = new CentralModel();
}
return instance;
}
}
public void Message(object sender, MessageReceivedEventArgs e)
{
var dresult = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, SomeTypeA>>(e.Message);
if (Handle.ContainsKey(dresult.Keys.ToList()[0]))
{
Handle[dresult.Keys.ToList()[0]](e);
}
}
}
}
SomeTypeA和SomeTypeB用于json序列化两种类型的消息。
SomeTypeA.cs
public class SomeTypeA
{
public string Name { get; set; }
public string Work { get; set; }
public string ID { get; set; }
public int value { get; set; }
public string Department { get; set; }
}
SomeTypeB.cs
public class SomeTypeB
{
public string Name { get; set; }
public string Work { get; set; }
public string ID { get; set; }
public int value { get; set; }
}
我在手机上做这个,所以代码示例可能看起来很垃圾,抱歉。
首先,如果您打算使用自己的类来定义JSON模型,那么实际上并不需要Newtonsoft。这是一个额外的组装,你必须正确授权。使用程序集中内置的JavaScriptSerializer
System.Web.Extensions
如果要将数据反序列化到字典中,只需使用内置的类。
参考此url创建可用于反序列化JSON数据的类:json2csharp
对于这样的JSON
{
"name": "My Name",
"age": "22",
"info": {
"social": [
"Facebook", "Twitter", "Google+"
]
}
}
c#就像
public class Info
{
public List<string> social { get; set; }
}
public class RootObject
{
public string name { get; set; }
public string age { get; set; }
public Info info { get; set; }
}
...
RootObject JSON= new JavaScriptSerializer().Deserialize<RootObject>(myJSONData);
...
然后,您可以将RootObject绑定到列表视图,并在数据绑定中使用不同的属性来获取信息。