当前位置:编程学习 > wap >>

Windows Phone 7 自定义事件

  在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("成功"));
          &nbs

补充:移动开发 , Windows Phone ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,