2015-05-15 55 views
0

我正在尝试在win8中构建通用应用程序,其中一个功能是显示连接状态。状态显示为一个按钮,如果处于活动状态,则为“绿色”,如果处于非活动状态,则为“红色”通用应用程序网络连接状态

这里是网络检测代码:

 public class InternetConnectionChangedEventArgs : EventArgs 
{ 
    public InternetConnectionChangedEventArgs(bool isConnected) 
    { 
     this.isConnected = isConnected; 
    } 
    private bool isConnected; 

    public bool IsConnected 
    { 
     get { return isConnected; } 
    } 
} 

public static class Network 
{ 
    public static event EventHandler<InternetConnectionChangedEventArgs> 
     InternetConnectionChanged; 

    static Network() 
    { 
     NetworkInformation.NetworkStatusChanged += (s) => 
     { 
      if (InternetConnectionChanged != null) 
      { 
       var arg = new InternetConnectionChangedEventArgs(IsConnected); 
       InternetConnectionChanged(null, arg); 
      } 
     }; 
    } 

    public static bool IsConnected 
    { 
     get 
     { 
      var profile = NetworkInformation.GetInternetConnectionProfile(); 
      var isConnected = (profile != null 
       && profile.GetNetworkConnectivityLevel() == 
       NetworkConnectivityLevel.InternetAccess); 
      return isConnected; 
     } 
    } 
} 

所以在最后我调用函数来设置按钮的颜色,但却系统抛出一个异常,指出“应用程序正在使用线程编组为一个不同的线程“

这是Main()构造函数中的代码。

该应用抛出异常一旦网络电缆被拉离..

Network.InternetConnectionChanged +=async(s,e)=> 
      { 
       await Dispatcher.RunAsync(CoreDispatcherPriority.Normal,() => 
       { 
        isInternetON=e.IsConnected; 
       }); 

       SetConnectionStaus(isInternetON); 


      }; 

我的猜测是我打电话一个线程从ANOTHER同时更新按钮的颜色..... KINDLY帮助!

回答

0

您可以使用此代码段更新来自非UI威胁UI属性:

await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,() => 
{ 
//Do thing/change value here 
});