#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 .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: