简体   繁体   中英

Binding WPF Events to MVVM ViewModel Commands in code behind of View

I got the below solution in XAML side to bind an event to command and it works just fine .

References

xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

Button Definition :

<Button>
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="MouseEnter" >
            <i:InvokeCommandAction Command="{Binding FooCommand}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</Button>

Problem: Now I need to do the same thing in code behind for my object which is a FrameworkElementFactory but I can't figure it out , I thought maybe some one can help me.

here is where I stopped:

        FrameworkElementFactory newLabel = new FrameworkElementFactory(typeof(Label));
        newLabel.SetValue(Label.BackgroundProperty, Brushes.DarkMagenta);

        var eventTrigger = new System.Windows.Interactivity.EventTrigger("MouseDown");
        var invokeCommandAction = new System.Windows.Interactivity.InvokeCommandAction()
            {
                CommandName = "FooCommand",
                CommandParameter = new Object()
            };

any help please?

Thanks in advance , Farzad

Not quite sure if this is the only way but you could probably add the trigger on-load by using Interaction.GetTriggers :

//<Your other code>
eventTrigger.Actions.Add(invokeCommandAction);

RoutedEventHandler loadedHandler = null;
loadedHandler = new RoutedEventHandler((s, _) =>
 {
     var label = s as Label;
     var triggers = Interaction.GetTriggers(label);
     triggers.Add(eventTrigger);
     label.Loaded -= loadedHandler;
 });
newLabel.AddHandler(FrameworkElement.LoadedEvent, loadedHandler);

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