Wpf从网络向应用程序的不同部分提供数据

时间:2015-09-01 14:26:10

标签: c# wpf

我有一个从Web服务器获取数据的WPF应用程序。

它包含两个视图

  • LeftView
  • RightView

三种模式

  • LeftModel
  • RightModel
  • CentralModel

和两个ViewModels

  • LeftViewModel
  • RightViewModel

我只会展示LeftViewLeftViewModelLeftModelCentralModel(代码太多)。您可以找到整个项目here

我猜主要的问题是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; }
}

1 个答案:

答案 0 :(得分:0)

我在手机上这样做,所以代码示例可能看起来很垃圾,抱歉。

首先,如果您要使用自己的类来定义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绑定到列表视图,并使用数据绑定中的不同属性来获取信息。

相关问题