WPF Gotcha: Mouse* Event With a Backgroundless StackPanel

WPF’s StackPanel (like many WPF containers and controls) has a few events you can tap into for mouse-related handling, including MouseDown, MouseLeftButtonDown, and MouseRightButtonDown. Adding an event handler is as simple as:

this._someStackPanel.MouseDown += (sender, args) => { Console.WriteLine("Hi mom!"); };

However, you might be surprised to find that clicking on your stack panel doesn’t trigger the event. Even more puzzling, if you’ve added this event handler to your Page or UIControl base, it still doesn’t fire — but it works for other controls!

Why?

The answer is surprisingly simple (and lame); StackPanel has a default background of “nothing” — that is to say, no colour, with no opacity. It’s invisible. When you set a background, the event handler fires as expected.

Personally, I find this inconsistent and perplexing; this occurs even when the StackPanel is visible, and indeed, other child controls within it are visible; yet the CLR refuses to trigger the event unless you’ve specified a non-transparent background.

The upside is, at least it’s easy to fix — pick any colour (and any transparency) background, and the event handlers fire.

About Ashiq Alibhai, PMP

Ashiq has been coding C# since 2005. A desktop, web, and RIA application developer, he's touched ASP.NET MVC, ActiveRecord, Silverlight, NUnit, and all kinds of exciting .NET technologies. He started C# City in order to accelerate his .NET learning.
This entry was posted in Core .NET, WPF and tagged , . Bookmark the permalink.

3 Responses to WPF Gotcha: Mouse* Event With a Backgroundless StackPanel

  1. TMox says:

    Thank you.

  2. Timo Paschke says:

    Thank you very much – I searched for a long time for a reason for this creepy behaviour.
    You saved me a lot of time!

  3. Ashiq Alibhai, PMP says:

    Glad it helped you guys out. I spent a long time pulling my hair out before discovering this (deceivingly) simple solution :)

Leave a Reply

Your email address will not be published. Required fields are marked *