简体   繁体   中英

Add additional string parameter into DispatcherTimer EventHandler

How can I add extra string parameter into Dispatchertimer Eventhandler ?.

I would like achieve something like this:

string ObjectName = "SomeObjectName";
System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick(ObjectName));

And function:

private void dispatcherTimer_Tick(object sender, EventArgs e, string ObjectName)
{
    [...]
}

How Can I achieve that?

Edit:

My intention is add some animation for moving object. I've got canvas with few objects. I can move this objects on canvas by mouse clicking, i would like to add animations for this movement.

You can use a closure for that:

... 
{    
    string objectName = "SomeObjectName";
    var dispatcherTimer = new DispatcherTimer();

    dispatcherTimer.Tick += (sender, e) => { myTick(sender, e, objectName); };
}

private void myTick(object sender, EventArgs e, string objectName)
{
    [...]
}

Note, though, that the variable objectName is captured, rather than it's current value. That means if you do this:

... 
{    
    string objectName = "SomeObjectName";
    var dispatcherTimer = new DispatcherTimer();

    dispatcherTimer.Tick += (sender, e) => { myTick(sender, e, objectName); };
    objectName = "SomeOtherObjectName";
}

myTick will be called with SomeOtherObjectName , which might be counter-intuitive at a first glance. The reason for this is that, under the hood, a separate object instance with an objectName field is created -- very similar to what Chris' solution is doing explicitly.

You can use this trick to pass along as much data as you'd like:

class Foo
{
    public string PropertyA { get; set; }
    public string PropertyB { get; set; }
    // ...

    public void OnTick( object sender, EventArgs e )
    {
        // logic here
    }
}

var f = new Foo() { PropertyA = "some stuff here",
                    PropertyB = "some more stuff here" };
dispatcherTimer.Tick += f.OnTick;

Obviously, if you only ever have one event handler for the same timer you could just as well store the required data in whatever class is using this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM