在Windows 8应用程序中为DispatcherTimer的Tick事件定义事件处理程序

时间:2012-05-05 17:40:57

标签: windows-8

我正在Windows 8 Visual Studio 11中开发一个应用程序,我想为DispatcherTimer实例定义一个事件处理程序,如下所示:

public sealed partial class BlankPage : Page
    {

        int timecounter = 10;
        DispatcherTimer timer = new DispatcherTimer();
        public BlankPage()
        {
            this.InitializeComponent();
            timer.Tick += new EventHandler(HandleTick);
        }

        private void HandleTick(object s,EventArgs e)
        {

            timecounter--;
            if (timecounter ==0)
            {
                //disable all buttons here
            }
        }
        .....
}

但是我得到以下错误:

Cannot implicitly convert type 'System.EventHandler' to 'System.EventHandler<object>'

我是widows 8应用的新手开发者。

你能帮帮我吗?

3 个答案:

答案 0 :(得分:8)

几乎拥有它:)你不需要实例化一个新的eventhandler对象,你只需要指向处理事件的方法。因此,一个事件处理程序。

        int timecounter = 10;
    DispatcherTimer timer = new DispatcherTimer();
    public BlankPage()
    {
        this.InitializeComponent();

        timer.Tick += timer_Tick;
    }

    protected void timer_Tick(object sender, object e)
    {
        timecounter--;
        if (timecounter == 0)
        {
            //disable all buttons here
        }
    }

尝试阅读代表以了解事件Understanding events and event handlers in C#

答案 1 :(得分:3)

您的代码期望HandleTick有两个Object参数。不是对象参数和EventArg参数。

private void HandleTick(object s, object e)

不是

private void HandleTick(object s,EventArgs e)

这是对Windows 8的更改。

答案 2 :(得分:2)

WinRT比标准的.NET Runtime更多地使用泛型。 DispatcherTimer.Tick为defined in WinRT is here

public event EventHandler<object> Tick

WPF DispatcherTimer.Tick is here     公共事件EventHandler Tick

另请注意,您不必使用标准命名方法来创建事件处理程序。您可以使用lambda来完成它:

int timecounter = 10;
DispatcherTimer timer = new DispatcherTimer();
public BlankPage()
{
    this.InitializeComponent();

    timer.Tick += (s,o)=>
    {
       timecounter--;
       if (timecounter == 0)
       {
           //disable all buttons here
       }
    };
}