2015-12-21 166 views
4

我刚开始用C#WPF学习Windows应用程序开发,我们都被赋予自我学习项目,开发一个Windows应用程序。我正在尝试创建应用程序到聊天客户端到客户端。我创建了一个类MainWindow.xaml和MainWindow.xaml.cs来处理它。当我从主窗体调用该类时,我收到以下错误。C#WPF收到错误 - System.InvalidOperationException:

enter image description here

而且这是两个阶级:

<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()); 
     } 
    } 
} 

}

回答

2

你正试图从一个background thread访问GUI item。 可以使用Dispatcher做的main thread

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

不管怎样,在WPF的推荐方式与GUI交互是DataBinding以及与MVVM模式关注点分离。

+0

是否需要创建新类或添加它? – Hunde

+0

不,只需替换导致异常的现有行:'listMessage.Items.Add(“Merid:”+ recievedMessage);' –

+0

我试过那个。它可以工作,但会显示以下文本:'System.Windows.Controls.TextBox'作为发件人名称和发送文本之间的错误。例如,这是意想不到的输出:'Merid:System.Windows.Controls.TextBox:Hi' – Hunde