Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom attached events in WPF

I might be getting the terminology wrong here, but I think I'm trying to create an attached event.

In the Surface SDK, you can do things like:

<Grid Background="{StaticResource WindowBackground}" x:Name="Foo" s:SurfaceFrameworkElement.ContactChanged="Foo_ContactChanged"/>

I want to create a custom event for which a handler can be added in XAML in the same way, but I'm having trouble.

I can create a custom routed event, but the XAML intellisense doesn't see it and the event handler isn't added if I just type it in regularly. Here is my event definition:

public static class TagRectEvents
{
    public static readonly RoutedEvent TagRectEnterEvent = EventManager.RegisterRoutedEvent(
        "TagRectEnter", RoutingStrategy.Bubble, typeof( RoutedEventHandler ), typeof( TagRectEvents ) );

    public static void AddTagRectEnterHandler( DependencyObject d, RoutedEventHandler handler )
    {
        UIElement element = d as UIElement;
        if ( element == null )
        {
            return;
        }
        element.AddHandler( TagRectEvents.TagRectEnterEvent, handler );
    }

    public static void RemoveTagRectEnterHandler( DependencyObject d, RoutedEventHandler handler )
    {
        UIElement element = d as UIElement;
        if ( element == null )
        {
            return;
        }
        element.RemoveHandler( TagRectEvents.TagRectEnterEvent, handler );
    }
}

Am I just going about it all wrong? All of the "attached behavior" examples I see are more about adding an attached property, and then doing things with elements that set that property.

like image 894
Josh Santangelo Avatar asked Nov 15 '22 15:11

Josh Santangelo


1 Answers

You must either be not mapping the namespace, and/or attaching event like local:TagRectEvents.TagRectEnterEvent . You have to use TagRectEnter, and not TagRectEnterEvent.

Namespace mapping :

 xmlns:local="clr-namespace:WpfInfrastructure.WpfAttachedEvents"

Usage :

<Button Content="Press" local:TagRectEvents.TagRectEnter="MyHandler" Margin="25,43,36,161" />

Handler :

    public void MyHandler(object sender, RoutedEventArgs e)
    {
        System.Diagnostics.Debug.WriteLine("Hurray!");
    }

I used your code, it works correctly here.

like image 74
AnjumSKhan Avatar answered Dec 26 '22 13:12

AnjumSKhan