David Ly
David Ly

Reputation: 31606

(WPF) How do you bind to IsMouseOver on a usercontrol

Edit: The original premise of the question was incorrect so revised the question:

Basically I want a button to be visible only when the mouse is over the containing user control. Here is the simplified versin of what I have:

<UserControl
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="MyNamespace.MyUserControl"
    x:Name="myUserControl">
    <Textbox>Some Text</Textbox>
    <Button Visibility="{Binding ElementName=myUserControl, Path=IsMouseOver, Converter={StaticResource mouseOverVisibilityConverter}}" />
</UserControl>

Which works if the mouse is over the text box, but not anywhere else in the user control.

Upvotes: 2

Views: 7585

Answers (3)

David Ly
David Ly

Reputation: 31606

I revised the question once Thomas pointed out the false assumption in my original question which lead me to discover the real reason it wasn't working in this post.

Basically the user control has a null background (as opposed to transparent) which apparently makes it invisible to the mouse, even with IsHitTestVisible set to true, so the solution was to add Background="Transparent" to the user control.

Upvotes: 6

Thomas Levesque
Thomas Levesque

Reputation: 292685

I realized that UserControl doesn't have a IsMouseOver property

But it does... IsMouseOver is defined in the UIElement class, from which UserControl (indirectly) inherits

Upvotes: 2

Joshua
Joshua

Reputation: 43327

You could implement that property in a derived class. I've had to do this kind of thing before.

Private _IsMouseOver As Boolean = False

Protected Overrides Sub OnMouseEnter(ByVal sender As Object, ByVal e As MouseEventArgs)
     _IsMouseOver = True
     MyBase.OnMouseEnter(sender, e)
End Sub

Protected Overrides Sub OnMouseLeave(ByVal sender As Object, ByVal e As MouseEventArgs)
     _IsMouseOver = False
     MyBase.OnMouseLeave(sender, e)
End Sub

Public ReadOnly Property IsMouseOver As Boolean()
    Get
        Return _IsMouseOver
    End Get
End Property

Upvotes: 1

Related Questions