7

我的问题是如何在 Dispatchertimer.Tick 事件中发送一些参数,这里是代码:我想要的是在 dispatcheTimer_Tick 接收一个整数值

    dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);

    private void dispatcherTimer_Tick(object sender, EventArgs e)
    {
        //.Text = DateTime.Now.Second.ToString();

    }

我想做的是这样的

    private void dispatcherTimer_Tick(object sender, EventArgs e,int a)
    {
        //.Text = DateTime.Now.Second.ToString();

    }

如何从调用点发送值?

4

2 回答 2

7

While there are a number of ways, I find it most convenient to use anonymous methods to close over variables when doing this:

dispatcherTimer.Tick += (s, args) => myControl.Text = DateTime.Now.Second.ToString();

If you have a handful of lines you could also do something more like:

int number = 5;
dispatcherTimer.Tick += (s, args) => 
{
    string value = someMethod();
    string otherValue = DateTime.Now.Second.ToString()
    myControl.Text = value + otherValue + number;
}

If you have more than just a handful of lines then you probably still want another method, but you can use a lambda to call that method:

int value = 5;
dispatcherTimer.Tick += (s, args) => myRealMethod(someControl, value);

public void myRealMethod(Control someControl, int value)
{
    someControl.Text = value;
}

This is convenient for both ignoring parameters of the event handler's delegate when you don't need them (I almost never use sender, I pass the actual object myself if I need it so that it's not cast to object first.) as well as adding in additional local variables.

于 2012-11-06T17:28:57.840 回答
0

If you know a at the time you're attaching the event handler, you can do something like this:

int a = 0;
dispatcherTimer.Tick += (sender, e) => 
    {
       /* a is available here */
    };
于 2012-11-06T17:28:45.007 回答