在Windows Phone的應用開發裡面,對於事件這種東西我們可以隨處可見,系統本來就已經封裝好了各種各樣的事件機制,如按鈕的單擊事件等等的。在實際的開發中,我們需要自己去給相關的類自訂一些事件來滿足業務的要求,特別在使用觀察著模式的時候,在wp7中利用事件去實現是理所當然的。
自訂事件步驟有下面的幾個步驟:
1、繼承EventArgs類實現自己自訂的事件參數;
2、定義一個委託;
3、定義一個事件
4、添加事件。
下面來看一下一個Demo對自訂事件的實現,這個Demo只是對網路請求的狀態進行一個簡單的事件監控的調用處理:
自訂的事件參數類
StateChangedEventArgs.cs
using System;
namespace EventDemo
{
/// <summary>
/// 狀態事件
/// </summary>
public class StateChangedEventArgs : EventArgs
{
public readonly string NewState;
public readonly DateTime Timestamp;
public StateChangedEventArgs(string newstate)
{
this.NewState = newstate;
this.Timestamp = DateTime.Now;
}
}
}
在業務類裡面定義事件:
NetTask.cs
using System;
using System.Net;
using System.Threading;
using System.IO;
namespace EventDemo
{
public class NetTask
{
//定義委託
public delegate void StateChanged(NetTask sender, StateChangedEventArgs args);
//定義事件
public event StateChanged OnStateChanged;
//出事狀態
public string NetTaskName = "";
/// <summary>
/// 網路任務
/// </summary>
/// <param name="url"></param>
public void StartNetTask(string url)
{
bool success = false;
int attempt = 0;
while (attempt < 3)
{
AsyncCallback callback = null;
//開啟線程等待
ManualResetEvent webRequestWait = new ManualResetEvent(false);
Uri targetUri = new Uri(url);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetUri);
request.Method = "POST";
if (callback == null)
{
callback = delegate(IAsyncResult asRequest)
{
try
{
success = true;
webRequestWait.Set();
//……
}
catch
{
OnStateChanged(this, new StateChangedEventArgs("重試"));
webRequestWait.Set();
}
};
}
request.BeginGetRequestStream(callback, request);
//等待線程結束
webRequestWait.WaitOne();
if (success)
{
break;
}
attempt++;
Thread.Sleep(1000);
}
if (success)
{
OnStateChanged(this, new StateChangedEventArgs("成功"));
Thread.Sleep(50);
}
else
{
OnStateChanged(this, new StateChangedEventArgs("失敗"));
}
}
}
}
簡單的測試一下
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Button Content="測試網路" Height="72" HorizontalAlignment="Left" Margin="143,105,0,0" Name="button1" VerticalAlignment="Top" Width="202" Click="button1_Click" />
<TextBlock Height="50" HorizontalAlignment="Left" Margin="96,270,0,0" Name="textBlock1" Text="網路的狀態:" VerticalAlignment="Top" Width="126" />
<TextBlock Height="48" HorizontalAlignment="Left" Margin="34,326,0,0" Name="textBlock2" Text="" VerticalAlignment="Top" Width="377" />
</Grid>
MainPage.xaml.cs
using System.Windows;
using Microsoft.Phone.Controls;
namespace EventDemo
{
public partial class MainPage : PhoneApplicationPage
{
public MainPage()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
NetTask netTask = new NetTask();
netTask.OnStateChanged += OnStateChanged;
netTask.NetTaskName = "測試網路";
netTask.StartNetTask("http://www.cnblogs.com");
}
public void OnStateChanged(object sender, StateChangedEventArgs e)
{
NetTask temp = sender as NetTask;
textBlock2.Text = temp.NetTaskName + "," + e.NewState+","+e.Timestamp.ToLongTimeString();
}
}
}
啟動並執行效果如下: