Category Archives: Events

How to Attach to MouseDown Event on ListBox

I wanted to create drag and drop functionality between two list boxes – user should be able to drag items from one ListBox to another.
For test, I created MouseDown event handler for list boxes. Here is XAML for window with two list boxes side by side:


<Window x:Class="ListBoxMouseEvents.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="316" Width="655">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
            <ColumnDefinition Width="20"/>
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <ListBox x:Name="listBox1" Mouse.MouseDown="ListBox_MouseDown">
            <ListBoxItem>Lorem ipsum dolor sit amet,</ListBoxItem> 
        </ListBox>
        <ListBox Grid.Column="2" x:Name="listBox2" Mouse.MouseDown="ListBox_MouseDown">
            <ListBoxItem>Lorem ipsum dolor sit amet,</ListBoxItem>
        </ListBox> 
    </Grid>
</Window>

In codebehind, I added simple handler for the MouseDown events on both listboxes. Handler should popup messagebox with name of the listbox that triggered the event.


    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }

        private void ListBox_MouseDown(Object sender, MouseButtonEventArgs e)
        {
            ListBox listBox = (ListBox)sender;
            MessageBox.Show("MouseDown event on " + listBox.Name);
        }
    }

Press F5 and test. Clicked in the middle of the left listbox – MesasgeBox pops up with correct name. Same for right listbox. Then I accidentally clicked on that one item in the listbox and nothing happened. Item was selected, but no MessageBox. Obviously, ListBoxItem class handled event and it stopped propagating.

How routed events work in WPF

MouseDown is, like all mouse events in WPF, implemented as RoutedEvent. Mechanics of routed events is described in MSDN article: Routed Events OverView.
In WPF, events can be routed in three ways: bubbling, tunneling and direct routing. Direct routing is not interesting because event fires only in control where it originated. Bubbling and tunneling routing propagate event through the visual tree.

  • Bubbling routes event from control where event was invoked to successive parent elements until it reaches the root.
  • Tunneling routes event in opposite direction, starting with element tree root and propagates until it reaches control where it was invoked. These are called “Preview” events.

Bubbling and tunneling events are often implemented in pairs. Tunneling events are always invoked first, before corresponding bubbling event.
MouseDown is routed event that is routed by bubbling and his corresponding tunneling or preview event is PreviewMouseDown.

Routing MouseDown event in ListBox

ListBox control contains ItemsPresenter which contains ListBoxItems (there are other controls in between like border and scrollviewer, but they could be abstracted here because they by default handle MouseDown event same way as ItemsPresenter ). When I click inside ListBox, but not on ListBoxItem, MouseDown event is routed like this:

  • Event originates in ItemsPresenter which is first control to receive event. Default handler does not set Handled property to true and event is propagated to its parents, who also do not change Handled property, until it reaches the ListBox.
  • ListBox finds ListBox_MouseDown handler and it invokes it. Code shows MessageBox and does not change Handled property so event can be propagated further. If Window had MouseDown event handler, it would be invoked.

When I click on ListBoxItem inside ListBox following happens:

  • ListBoxItem is first control that receives event. It’s MouseDown handler have code that deals with the selected item inside ListBox (sets properties related to selection and changes visual appearance). Finally it sets Handled property to true. This suggests that event does not need further handling.

Work around: how to handle ‘handled’ routed events

Fortunately, there are two ways to work around this situation:

  • Use the “Preview” event which happens before the bubbling event. This event can be added in XAML. When using this approach, you should be careful not to set Handled property to true, because it will prevent bubbling events to be invoked.
  • Add handler by using the handledEventsToo signature of AddHandler(RoutedEvent, Delegate, Boolean). Limitation of this workaround is that it can be set only in code, not in XAML.

More details on this can be found in last section of MSDN article Marking Routed Events as Handled, and Class Handling.
Finally, here is the code that uses both approaches – one ListBox have preview event attached, while the other has handler added in code.
XAML:


<Window x:Class="ListBoxMouseEvents.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="316" Width="655">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
            <ColumnDefinition Width="20"/>
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <ListBox x:Name="listBox1" Mouse.PreviewMouseDown="ListBox_MouseDown">
            <ListBoxItem>Lorem ipsum dolor sit amet,</ListBoxItem> 
            <ListBoxItem>consectetur adipiscing elit. </ListBoxItem>
            <ListBoxItem>Duis mollis egestas ornare. </ListBoxItem>
        </ListBox>
        <ListBox Grid.Column="2" x:Name="listBox2" >
            <ListBoxItem>Lorem ipsum dolor sit amet,</ListBoxItem>
            <ListBoxItem>consectetur adipiscing elit.</ListBoxItem>
            <ListBoxItem>Duis mollis egestas ornare.</ListBoxItem>
        </ListBox> 
    </Grid>
</Window>

CodeBehind:


    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            // Add handler. Note third parameter: handledEventsToo = true
            listBox2.AddHandler(UIElement.MouseDownEvent, 
                new MouseButtonEventHandler(ListBox_MouseDown), true);
        }

        private void ListBox_MouseDown(Object sender, MouseButtonEventArgs e)
        {
            ListBox listBox = (ListBox)sender;
            this.Title = "MouseDown event on " + listBox.Name;
        }
    }

Note that in this version text is displayed in the title of the window instead of MessageBox. I changed it because showing message box in PreviewMouseDown event was interfering with event propagation and item in left list box was not selected after click – looked like click never happened. It probably has something to do with the fact that there were other mouse events happening when I was closing message box. So, be careful with actions in preview event.

For drag/drop handling I will use second approach – adding handler that receives handled events. Drag and drop functionality needs information about selected item. I could get that myself in preview event, but why, when there is code in event handler of ListBoxItem.