wpf 在 Dispatchertimer.Tick 事件中发送一个额外的参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13256164/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 06:06:25  来源:igfitidea点击:

send a extra argument in Dispatchertimer.Tick event

c#wpfdispatchertimer

提问by ahmad05

my question is how can i send some arguments in Dispatchertimer.Tick event here is the code: what i wanted to is receive a integer value at dispatcheTimer_Tick

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

    dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);

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

    }

what i wanted to do is something like this

我想做的是这样的

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

    }

how to send a value from a calling point??

如何从调用点发送值?

回答by Servy

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:

如果您的代码不止几行,那么您可能还需要另一种方法,但您可以使用 lambda 来调用该方法:

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 objectfirst.) as well as adding in additional local variables.

这对于在不需要事件处理程序委托的参数时忽略它们很方便(我几乎从不使用sender,如果需要,我自己传递实际对象,以便它不会object首先转换为。)以及添加额外的局部变量。

回答by Austin Salonen

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

如果您a当时知道要附加事件处理程序,则可以执行以下操作:

int a = 0;
dispatcherTimer.Tick += (sender, e) => 
    {
       /* a is available here */
    };