1

I have the following routed event:

public static readonly RoutedEvent ItemMouseDownEvent = EventManager.RegisterRoutedEvent(
    "ItemMouseDown", RoutingStrategy.Bubble, typeof(ItemMouseDownEventHandler), typeof(BindableGrid));

public delegate void ItemMouseDownEventHandler(object sender, ItemMouseDownEventArgs e);

public class ItemMouseDownEventArgs : RoutedEventArgs
{
    public object Item { get; set; }
}

public event ItemMouseDownEventHandler ItemMouseDown
{
    add { AddHandler(ItemMouseDownEvent, value); }
    remove { RemoveHandler(ItemMouseDownEvent, value); }
}

And I'm firing it like so (this code does get called, I set a breakpoint):

var args = new ItemMouseDownEventArgs
{
    Item = ((FrameworkElement)sender).DataContext,
    RoutedEvent = ItemMouseDownEvent
};
RaiseEvent(args);

I have a XAML page consuming the event:

<local:BindableGrid x:Name="starSystemMap" ArraySource="{Binding SpaceObjectArray}" CellSize="64" BackgroundImage="/Images/Starfield.png" ItemMouseDown="starSystemMap_ItemMouseDown">
...
</local:BindableGrid>

And the event handler (WIP):

private void starSystemMap_ItemMouseDown(object sender, BindableGrid.ItemMouseDownEventArgs e)
{
    switch (e.Item)
    {
        case null:
            MessageBox.Show("Space... the final frontier... is very, very empty...");
            break;
    }
}

Now even though the event is being raised, the event handler never gets called - why is this? How can I get the event handler to be called for my custom routed event?

ekolis
  • 6,270
  • 12
  • 50
  • 101
  • That event, `ItemMouseDown`, would it fire if you registered a handler like `void h(object s, EventArgs e) => MsgBox.Show(s);` I suspect not. Perhaps your event declaration is not quite right. Events are declared with the `event` keyword which is special. – Aluan Haddad Sep 23 '18 at 20:28
  • 1
    Oops, I left that part out; I will add the event declaration to my post. – ekolis Sep 23 '18 at 20:50
  • Do the add and remove handlers run? – Aluan Haddad Sep 23 '18 at 20:52
  • That's odd; I set a breakpoint on the Add/RemoveHandler lines, and they aren't being executed. Is something wrong with my XAML where I declared the event handlers? – ekolis Sep 23 '18 at 20:55
  • Aha! I had some overlays displaying on top of my BindableGrid; if I remove the overlays, the event works. How can I make the click go "through" the overlays (additional BindableGrids) and reach the grid I'm working with? – ekolis Sep 23 '18 at 20:59
  • I don't recall offhand. Maybe don't bubble. – Aluan Haddad Sep 23 '18 at 21:00
  • 1
    Found an answer! https://stackoverflow.com/a/988314/1159763 => need to set IsHitTestVisible="False" on the overlays. – ekolis Sep 23 '18 at 21:01

1 Answers1

1

I had additional BindableGrid overlays on top of the BindableGrid I was trying to click; I had to set IsHitTestVisible="False" on the overlays so the click would go "through" to the grid I wanted to click.

ekolis
  • 6,270
  • 12
  • 50
  • 101