#678 – Hide an Element from the Mouse with IsHitTestVisible Property

You can completely hide a user interface element from the mouse by setting its IsHitTestVisible property to false.  When this property is false, no mouse related events will be fired for that control.

In the example below, one Label has its IsHitTestVisible property set to false.

    <StackPanel>
        <Label Content="Mouse Sees Me" Background="AliceBlue" Margin="10"
               MouseMove="Label_MouseMove_1"/>
        <Label Content="Mouse Doesn't see Me" Background="Beige" Margin="10"
               IsHitTestVisible="False"
               MouseMove="Label_MouseMove_2"/>
    </StackPanel>

Assume that we try to report the mouse position in both event handlers:

        private void ReportMouse(string element, MouseEventArgs e)
        {
            Point p = e.GetPosition(null);
            Console.WriteLine(string.Format("{0} sees mouse at ({1},{2})", element, p.X, p.Y));
        }

        private void Label_MouseMove_1(object sender, MouseEventArgs e)
        {
            ReportMouse("Label 1", e);
        }

        private void Label_MouseMove_2(object sender, MouseEventArgs e)
        {
            ReportMouse("Label 2", e);
        }

When we move the mouse over both labels at runtime, we only see output when it moves over label #1, which does not set IsHitTestVisible to false.

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a comment