The Networkchange,networkinterface two classes (both abstract) are provided in the SILVERLIGHT3.
The Networkaddresschanged event handler is implemented to detect the current online state, while the NetworkInterface
The Getisnetworkavailable () method of the class (returning the bool type) is used to determine whether the current is online. With these two classes,
can be very convenient for the implementation of dynamic detection of the current application is wired.
Here's a demo I wrote to illustrate how to use both methods, where the XAML code is as follows:
<UserControl x:Class="Off_Online.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300">
<Grid x:Name="LayoutRoot" Background="White">
<Grid.RowDefinitions>
<RowDefinition Height="150" />
<RowDefinition Height="150" />
</Grid.RowDefinitions>
<Image Width="100" Height="100" x:Name="StateIcon" Grid.Row="0" HorizontalAlignment="Center" />
<TextBlock Name="NetWorkState" Foreground="Red" FontSize="20" Grid.Row="1" FontWeight="Bold" HorizontalAlignment="Center" >当前状态未知</TextBlock>
</Grid>
</UserControl>
and the corresponding CS code is as follows:
Using System.Net.NetworkInformation;
Namespace Off_online
{
public partial class Mainpage:usercontrol
{
Public MainPage ()
{
InitializeComponent ();
This. Loaded + = new Routedeventhandler (mainpage_loaded);
}
void Mainpage_loaded (object sender, RoutedEventArgs e)
{
Networkchange.networkaddresschanged + = onnetworkaddresschanged;
Updatenetworkstate ();
}
void Updatenetworkstate ()
{
string state = Networkinterface.getisnetworkavailable ()? "Online": "Offline";
Stateicon.source = new System.Windows.Media.Imaging.BitmapImage (New Uri ("/images/" + state + ". jpg", urikind.relative)) ;
Networkstate.text = Networkinterface.getisnetworkavailable ()? "Online": "Off-line";
}
void Onnetworkaddresschanged (object sender, EventArgs e)
{
Updatenetworkstate ();
}
}
}