How to create EventToCommand in Code-Behind

Topics: Questions
Jun 14, 2012 at 12:05 PM

I want to create an EventToCommand in code-behind. This is what I have:

Binding commandParameterBinding = new Binding("EditValue") { Mode = BindingMode.OneWay, Source = this.testItem };        
Binding commandBinding = new Binding("TestCommand") { Mode = BindingMode.OneWay, Source = this.DataContext };

var testTrigger = new EventTrigger();
testTrigger.RoutedEvent = BaseEdit.KeyUpEvent;

EventToCommand testEventCommand = new EventToCommand();
BindingOperations.SetBinding(testEventCommand, EventToCommand.CommandProperty, commandBinding);
BindingOperations.SetBinding(testEventCommand, EventToCommand.CommandParameterProperty, commandParameterBinding);       

testTrigger.Actions.Add((TriggerAction)testEventCommand);

The last line is the Problem, the eventToCommnad is a generic triggerAction, and of course I can't cast it to its non-generic Baseclass.

So, what can I do?

Jun 14, 2012 at 12:14 PM

Nevermind, have to use "System.Windows.Interactivity.EventTrigger" instead of "System.Window.EventTrigger" class...

Coordinator
Jun 14, 2012 at 12:14 PM

Thanks for sharing this knowledge.

Jun 14, 2012 at 2:55 PM
Edited Jun 14, 2012 at 2:56 PM

The complete working solution, maybe someone don't know how to do this in code-behind (like me...):

 

var commandParameterBinding = new Binding("Text") { Mode = BindingMode.OneWay, Source = this.textBox1 };
var commandBinding = new Binding("TestCommand") { Mode = BindingMode.OneWay };

var testTrigger = new System.Windows.Interactivity.EventTrigger { EventName = "MouseDoubleClick" };

var testEventCommand = new EventToCommand();
BindingOperations.SetBinding(testEventCommand, EventToCommand.CommandProperty, commandBinding);
BindingOperations.SetBinding(testEventCommand, EventToCommand.CommandParameterProperty, commandParameterBinding);

testTrigger.Actions.Add(testEventCommand);

// Add trigger to target object System.Windows.Interactivity.Interaction.GetTriggers(textBox1).Add(testTrigger);