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.