Search code examples
c#wpfuser-controlseventhandler

How can you pass events from a UserControl to one of its children?


Assume you have a UserControl called ActionableListBox which is composed of a DockPanel that contains a Button and a ListBox.

Setting up ActionableListBox to expose the properties on the wrapped ListBox is simple. Just define the property on ActionableListBox and delegate the getter/setter down to the internal ListBox. Pretty straight forward.

What I'm not finding however is how to set up the ActionableListBox to 'pass thru' the events like SelectionChanged, etc. so I can use it in XAML. You can't 'delegate down' like with properties as an event handler can only appear on the left of an assignment operator.

So, short of being forced to convert this into a full-on CustomControl, is there any way to 'pass thru' the events so I can use this UserControl in XAML?


Solution

  • It's quite simple actually. Define SelectionChanged event for ActionableListBox. For ListBox's SelectionChanged create an event handler in ActionableListBox that in turn fires its own SelectionChanged.

        public event SelectionChangedEventHandler SelectionChanged;
        ...
        listBox.SelectionChanged += listBox_SelectionChanged;
        ...
        void listBox_SelectionChanged(object sender, SelectionChangedEventArgs args)
        {
            SelectionChanged?.Invoke(sender, args);
        }