#684 – Mouse Events Occur for the Element That the Mouse Is Over

Mouse events normally fire for the element that mouse is current positioned over.  In the example below, notice that the Source property for the event handler always refers to the Label that the mouse is currently positioned over.

    <StackPanel MouseDown="Label_MouseDown" MouseUp="Label_MouseUp" MouseMove="Label_MouseMove">
        <Label Content="Sistine" Background="ForestGreen" Padding="10,20"/>
        <Label Content="Buonarroti" Background="Peru" Padding="10,20"/>
    </StackPanel>

 

        private void Label_MouseDown(object sender, MouseButtonEventArgs e)
        {
            Label l = e.Source as Label;
            if (l != null)
                Console.WriteLine(string.Format("MouseDown on {0}", l.Content));
        }

        private void Label_MouseUp(object sender, MouseButtonEventArgs e)
        {
            Label l = e.Source as Label;
            if (l != null)
                Console.WriteLine(string.Format("MouseUp on {0}", l.Content));
        }

        private void Label_MouseMove(object sender, MouseEventArgs e)
        {
            Label l = e.Source as Label;
            if (l != null)
            {
                Point p = e.GetPosition(null);
                Console.WriteLine(string.Format("MouseMove on {0} at ({1},{2})", l.Content, p.X, p.Y));
            }
        }

If we press the mouse button while over one Label, move to the other Label and release the button, we get:

Advertisements