我尝试实现(在WPF,C#中)Ellipse
控件,该控件根据与google.com的连接来改变其颜色。如果与Google有连接,椭圆为绿色;否则它是红色的。
我是这样编码的:
XAML 代码
<Window.Resources>
<l:InternetConnectionToBrushConverter x:Key="InternetConnectionConverter" />
</Window.Resources>
<Grid>
<DockPanel LastChildFill="True">
<StatusBar Height="23" Name="statusBar1" VerticalAlignment="Bottom" DockPanel.Dock="Bottom">
<Label Content="Google connection:" Name="label1" FontSize="10" Padding="3" />
<Ellipse Name="ellipse1" Stroke="Black" Width="10" Height="10" Fill="{Binding Converter={StaticResource InternetConnectionConverter}}" Margin="0,4,0,0" />
</StatusBar>
</DockPanel>
</Grid>
和 C# 代码后面(值转换器和函数检查连接):
public class InternetConnectionToBrushConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (targetType != typeof(Brush))
throw new InvalidOperationException("The target must be a Brush!");
return CheckConnection("http://www.google.com/") == true ? Brushes.Green : Brushes.Red;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
/// <summary>
/// Checks connection to specified URL.
/// </summary>
/// <param name="URL"></param>
/// <returns><b>True</b> if there is connection. Else <b>false</b>.</returns>
private bool CheckConnection(String URL)
{
try
{
HttpWebRequest request = WebRequest.Create(URL) as HttpWebRequest;
request.Timeout = 15000;
request.Credentials = CredentialCache.DefaultNetworkCredentials;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
return response.StatusCode == HttpStatusCode.OK ? true : false;
}
catch (Exception e)
{
Debug.WriteLine(e.ToString());
return false;
}
}
}
它运作良好,但有两个问题:
- 检查连接需要一些时间,所以我认为我应该在新线程中进行(如果我错了,请告诉我原因)
- 更重要的是——它只检查一次与谷歌的连接,当程序开始运行时(尽管我使用绑定,所以我希望会有持续的连接监控)
我应该如何解决这个问题?
我想要持续监控连接,这样当我断开互联网连接时,Ellipse
控件会改变它的颜色。