Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Wpf从web向应用程序的不同部分提供数据_C#_Wpf - Fatal编程技术网

C# Wpf从web向应用程序的不同部分提供数据

C# Wpf从web向应用程序的不同部分提供数据,c#,wpf,C#,Wpf,我有一个从web服务器获取数据的WPF应用程序 它包含两个视图 LeftView RightView 三种模式 LeftModel RightModel CentralModel 和两个视图模型 LeftViewModel RightViewModel 我将只显示LeftView,LeftView模型,LeftModel,和CentralModel(代码太多)。你可以找到整个项目 我想主要的问题是UpdateCollection()与公共可观察集合项{get;set;}有高度耦合 因

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

它包含两个视图

  • LeftView
  • RightView
三种模式

  • LeftModel
  • RightModel
  • CentralModel
和两个视图模型

  • LeftViewModel
  • RightViewModel
我将只显示
LeftView
LeftView模型
LeftModel
,和
CentralModel
(代码太多)。你可以找到整个项目

我想主要的问题是
UpdateCollection()
公共可观察集合项{get;set;}
有高度耦合

因此,我觉得我无法将
UpdateCollection()
放在
CentralModel

我认为如果
UpdateCollection()
将位于
CentralModel
中会更好,如何做到这一点

工作逻辑非常简单,来自web服务器的传入消息添加到
公共字典句柄{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);
        }
    }
LeftView.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);
    }
}
}
namespace Server
{
class Program
{
    static void Main(string[] args)
    {
        ServerClass myServer = new ServerClass();
        myServer.Setup();
        myServer.Start();
    }
}
}
<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>
namespace WpfApplication139.ViewModels
{
public class LeftViewModel
{
    public LeftModel LM { get; set; }
    public LeftViewModel()
    {
        LM = new LeftModel();
    }
}
}
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;
                }
            }
        });
    }
}
}
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);
        }
    }
}
}
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; }
}
public class SomeTypeB
{
    public string Name { get; set; }
    public string Work { get; set; }
    public string ID { get; set; }
    public int value { get; set; }
}
LeftModel.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);
    }
}
}
namespace Server
{
class Program
{
    static void Main(string[] args)
    {
        ServerClass myServer = new ServerClass();
        myServer.Setup();
        myServer.Start();
    }
}
}
<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>
namespace WpfApplication139.ViewModels
{
public class LeftViewModel
{
    public LeftModel LM { get; set; }
    public LeftViewModel()
    {
        LM = new LeftModel();
    }
}
}
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;
                }
            }
        });
    }
}
}
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);
        }
    }
}
}
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; }
}
public class SomeTypeB
{
    public string Name { get; set; }
    public string Work { get; set; }
    public string ID { get; set; }
    public int value { get; set; }
}
SomeTypeB.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);
    }
}
}
namespace Server
{
class Program
{
    static void Main(string[] args)
    {
        ServerClass myServer = new ServerClass();
        myServer.Setup();
        myServer.Start();
    }
}
}
<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>
namespace WpfApplication139.ViewModels
{
public class LeftViewModel
{
    public LeftModel LM { get; set; }
    public LeftViewModel()
    {
        LM = new LeftModel();
    }
}
}
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;
                }
            }
        });
    }
}
}
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);
        }
    }
}
}
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; }
}
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数据的类:

所以,像这样使用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);
...
公共类信息
{
公共列表社交{get;set;}
}
公共类根对象
{
公共字符串名称{get;set;}
公共字符串年龄{get;set;}
公共信息{get;set;}
}
...
RootObject JSON=new JavaScriptSerializer()。反序列化(myJSONData);
...
然后可以将RootObject绑定到列表视图,并使用数据绑定中的不同属性来获取信息