Toggling visibility On Mouse Over

This is something I consider a good find because there is no logical explanation why it behaves as follows but the fact that it does, demands a blog post:

I had a stack panel with one text box and one button. This stack panel was part of my listbox item template hence repeated for each list item. I wanted to toggle the visibility of the button in my stack panel based on the mouse over status of the list item. So basically, when your roll your mouse over the listitem, i want that button to show up. I put the standard xaml as follows:

<StackPanel >
<TextBlock Text=”{Binding Path=Name}” />
<Button 
Visibility=”{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type StackPanel}} , Path=IsMouseOver, Converter={StaticResource BooleanToVisibilityConverter}}”/>
</StackPanel>

And guess what, the toggling was not working property! The button would show up when i roll mouse on the left side of stack panel but as soon as it comes near the button, the button would disappear. It looked really fiddly and funny since the button kept blinking randomly. There could be a logical explanation for this but in any case it was not how its supposed to behave because the button is inside the stack panel and as long as i have set an event on the mouse over of stackpanel, the button should respect that.

After some research, i discovered that if the background of the stack panel was set to a colour then this fiddly behaviour of the button would stop and the button would stay visible as long as i have mouse on any area of the entire Stackpanel. So finally i had to put a transparent background to the panel to make this thing work correctly.

<StackPanel Background=”Transparent”>
<TextBlock Text=”{Binding Path=Name}” />
<Button 
Visibility=”{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type StackPanel}} , Path=IsMouseOver, Converter={StaticResource BooleanToVisibilityConverter}}”/>
</StackPanel>

Advertisements