6

I have a simple user-control with an event:

using System.Windows;

namespace TriggersTest
{
    public partial class MyControl
    {
        public MyControl()
        {
            InitializeComponent();
        }

        public static readonly RoutedEvent ButtonPressedEvent =
            EventManager.RegisterRoutedEvent("ButtonPressed", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MyControl));

        public event RoutedEventHandler ButtonPressed
        {
            add { AddHandler(ButtonPressedEvent, value); }
            remove { RemoveHandler(ButtonPressedEvent, value); }
        }

        private void OnButtonClick(object sender, RoutedEventArgs e)
        {
            RaiseEvent(new RoutedEventArgs { RoutedEvent = ButtonPressedEvent });
        }
    }
}

And I want to catch this event in the other view:

<Window x:Class="TriggersTest.MainWindow"
        Name="Root"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
        xmlns:local="clr-namespace:TriggersTest"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <local:MyControl>
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="ButtonPressed">
                    <i:InvokeCommandAction Command="{Binding MyCommand, ElementName=Root}" />
                </i:EventTrigger>
            </i:Interaction.Triggers>
        </local:MyControl>
    </Grid>
</Window>

The event has been raised, but i:EventTrigger doesn't invoke a command.

How can I fix this?

tnw
  • 13,521
  • 15
  • 70
  • 111
Igorious
  • 81
  • 5
  • I have the exact same problem. A custom event is declared inside a UserControl. I am trying to bind it with a Command in my main View through interactivity in vain. The simpliest of the controls and code is used, like a TextBlock and a Grid. Nothing more. Have you resolved it? – Efthymios Jun 17 '20 at 10:12

1 Answers1

-1

Its all fine with your code. The binding is not working. I can tell just by looking at this.

Do not use ElementName inside InvokeCommandAction because InvokeCommandAction is not part of LogicalTree in WPF.

Just change your Binding or use x:Reference and everything should be fine.

dev hedgehog
  • 8,698
  • 3
  • 28
  • 55