WPF的Window_Loaded问题
请问下WPF中,我在Window_Loaded里面去连接socket,我测试在不连接网络的时候,我去连接,没连接上,但是也要保证软件界面可以启动并且把错误甩到GUI上,请问怎么弄?
private void Window_Loaded(object sender, RoutedEventArgs e)
{
test.OpenSocket();
}
public override bool OpenSocket()
{
try
{
System.Net.IPAddress ip = System.Net.IPAddress.Parse(_RobotIpAddr);
System.Net.IPEndPoint ipe = new System.Net.IPEndPoint(ip, _PortNo);
_socket = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork
, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
_socket.Connect(ipe);
if (!_socket.Connected)
throw new RobotConnectException("Open onnection failed!");
}
catch(Exception ex)
throw ex;
}
好像软件还是没能启动界面,请问怎么解决?
------解决方案--------------------
说一个大概的思路,主要是采用异步+绑定的思路
写一个Client的Class负责网络连接
Client可以考虑继承DependencyObject,其中Open后开线程建立Socket连接以及登录服务器
然后在Client放一个以来属性,IsConnect,当线程连接上后Invoke回来将IsConnect置为True
将MainWindow的Label中的Content绑定到Client的IsConnect依赖属性上即可