Search code examples
c#.netwpfexpression-blend

System.Windows.Interactivity.EventTrigger and custom controls with children


I have a problem with System.Windows.Interactivity.EventTrigger. It works perfectly when my CustomControl is a child of some standard WPF panel, but whenever I put it inside my CustomPanelControl, the Tap event is never subscribed to. If I change the base class of CustomPanelControl from FrameworkElement to Panel then it works. I'm assuming there is something I need to implement, but what?

CustomControl.cs:

public class CustomControl: FrameworkElement
{
    public void RaiseTap()
    {
        OnTap();
    }

    protected virtual void OnTap()
    {
        RaiseEvent(new RoutedEventArgs(TapEvent));
    }

    public static readonly RoutedEvent TapEvent = EventManager.RegisterRoutedEvent("Tap", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(CustomControl));

    public event RoutedEventHandler Tap
    {
        add { AddHandler(TapEvent, value); }
        remove { RemoveHandler(TapEvent, value); }
    }
}

CustomPanelControl.cs:

[ContentProperty("Children")]
public class CustomPanelControl: FrameworkElement
{
    public UIElementCollection Children { get; private set; } 

    public CustomPanelControl()
    {
        Children = new UIElementCollection(this, this);
    }
}

Solution

  • I have found the solution. For Children property to work GetVisualChild and VisualChildrenCount need to be overridden.

    This article proved to be very useful (A Brief Look at UIElementCollection section): http://www.codeproject.com/Articles/24982/Conceptual-Children-A-powerful-new-concept-in-WPF