C#WPF获取错误 – System.InvalidOperationException:

我刚刚开始使用C#
WPF学习
Windows应用程序开发,并且我们已经获得了自学项目来开发一个Windows应用程序.我正在尝试创建聊天客户端到客户端的应用程序.我已经创建了一个MainWindow.xaml和MainWindow.xaml.cs类来处理它.当我从主窗体调用该类时,我收到以下错误.

《C#WPF获取错误 – System.InvalidOperationException:》

这些是两类:

<Window x:Class="Chat_Client.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:Chat_Client"
    mc:Ignorable="d"
    Title="Chat: Client-to-Client" Height="450" Width="625">
<Grid>
    <Label x:Name="label" Content="IP" HorizontalAlignment="Left"   Margin="39,52,0,0" VerticalAlignment="Top"/>
    <Label x:Name="label1" Content="Port" HorizontalAlignment="Left" Margin="39,100,0,0" VerticalAlignment="Top"/>
    <Label x:Name="label2" Content="IP" HorizontalAlignment="Left" Margin="287,59,0,0" VerticalAlignment="Top"/>
    <Label x:Name="label3" Content="Port" HorizontalAlignment="Left" Margin="287,100,0,0" VerticalAlignment="Top" RenderTransformOrigin="-0.037,-0.343"/>
    <TextBox x:Name="textLocalIp" HorizontalAlignment="Left" Height="23" Margin="98,59,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
    <TextBox x:Name="textLocalPort" HorizontalAlignment="Left" Height="23" Margin="98,104,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
    <TextBox x:Name="textFriendsIp" HorizontalAlignment="Left" Height="23" Margin="342,59,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" TextChanged="textBox2_TextChanged"/>
    <TextBox x:Name="textFriendsPort" HorizontalAlignment="Left" Height="23" Margin="342,104,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
    <Button x:Name="button" Content="Start" HorizontalAlignment="Left" Margin="488,58,0,0" VerticalAlignment="Top" Width="96" Click="button_Click"/>
    <ListBox x:Name="listMessage" HorizontalAlignment="Left" Height="156" Margin="39,151,0,0" VerticalAlignment="Top" Width="423"/>
    <TextBox x:Name="textMessage" HorizontalAlignment="Left" Height="39" Margin="39,343,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="423"/>
    <Button x:Name="button1" Content="Send" HorizontalAlignment="Left" Margin="488,362,0,0" VerticalAlignment="Top" Width="96" Click="button1_Click"/>
    <Label x:Name="label4" Content="C1" HorizontalAlignment="Left" Margin="98,28,0,0" VerticalAlignment="Top" RenderTransformOrigin="-0.585,0.964"/>
    <Label x:Name="label5" Content="C2" HorizontalAlignment="Left" Margin="342,28,0,0" VerticalAlignment="Top" RenderTransformOrigin="0.105,1.107"/>
</Grid>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Net;
using System.Net.Sockets;
namespace Chat_Client
{
public partial class MainWindow : Window
{
    Socket sck;
    EndPoint epLocal, epRemote;
    public MainWindow()
    {
        InitializeComponent();
        sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
        textLocalIp.Text = GetLocalIP();
        textFriendsIp.Text = GetLocalIP();
    }
    private string GetLocalIP()
    {
        IPHostEntry host;
        host = Dns.GetHostEntry(Dns.GetHostName());
        foreach(IPAddress ip in host.AddressList)
        {
            if (ip.AddressFamily == AddressFamily.InterNetwork)
            {
                return ip.ToString();
            }
        }
        return "127.0.0.1";
    }
    private void MessageCallBack(IAsyncResult aResult)
    {
        try
        {
            int size = sck.EndReceiveFrom(aResult, ref epRemote);
            if (size > 0)
            {
                byte[] recievedData = new byte[1464];
                recievedData = (byte[])aResult.AsyncState;
                ASCIIEncoding eEncoding = new ASCIIEncoding();
                string recievedMessage = eEncoding.GetString(recievedData);
                listMessage.Items.Add("Merid: " + recievedMessage);
            }
            byte[] buffer = new byte[1500];
            sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
        }
        catch(Exception exp)
        {
            MessageBox.Show(exp.ToString());
        }
    }
    private void textBox2_TextChanged(object sender, TextChangedEventArgs e)
    {
    }
    private void button_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            epLocal = new IPEndPoint(IPAddress.Parse(textLocalIp.Text), Convert.ToInt32(textLocalPort.Text));
            sck.Bind(epLocal);
            epRemote = new IPEndPoint(IPAddress.Parse(textFriendsIp.Text), Convert.ToInt32(textFriendsPort.Text));
            sck.Connect(epRemote);
            byte[] buffer = new byte[1500];
            sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
            button.Content = "Connected";
            button.IsEnabled = false;
            button1.IsEnabled = true;
            textMessage.Focus();
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }
    private void button1_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
            byte[] msg = new byte[1500];
            msg = enc.GetBytes(textMessage.Text);
            sck.Send(msg);
            listMessage.Items.Add("Bod: "+textMessage);
            textMessage.Clear();
        }
        catch(Exception excp)
        {
            MessageBox.Show(excp.ToString());
        }
    }
}

}

最佳答案 您正在尝试从后台线程访问GUI项目.

您可以使用Dispatcher在主线程上执行此操作:

Dispatcher.Invoke(new Action(() => listMessage.Items.Add("Merid: " + recievedMessage)));

无论如何,WPF中与GUI交互的推荐方式是DataBinding并将关注点与MVVM模式分离.

点赞