开发者

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 F开发者_StackOverflow社区rameworkElementFactory(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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜