Search code examples
xamlwindows-8microsoft-metro

Show border control on hover


I've got a Border control, which holds an Image control. Basicly i want to show the Border control if the Image control is hovered. Something similar to the css :hover effect.

What's the easiest way achieve this?


Solution

  • There are so many ways to achieve this, and it all depends on what your setup is.

    • Is it for just one isolated image, or do you want to be able to reuse this functionality elsewhere?
    • Is your image inside a DataTemplate for a ListView or some other items control?
    • Would you be OK by writing code-behind to achieve this, or preferably a XAML-only solution? (Hopefully the latter.)
    • Etc.

    If it's for just one image, you could handle the PointerEntered and PointerExited events on the image control to set the border's BorderBrush color to yellow (for example) and transparent, respectively. Since you said you're very new to XAML, this is the only "easiest" solution that I can offer. Maybe someone else can suggest other simple alternatives. Unfortunately, there is no ":hover"-like styling out of the box. You have to write this functionality yourself.


    My preferred solution is to bundle this functionality up into some kind of reusable component. Some solutions that come to mind:

    1. Create a UserControl housing a Border and Image with the necessary code-behind to handle pointer enter and exit events.
    2. Create a new templated ContentControl, allowing you to set any arbitrary UIElement inside the Border. This also allows you to use TemplateBindings to set things like the BorderBrush from outside the template.
    3. Create a Behavior (Blend SDK) that can be attached to your Border that houses the necessary logic.

    On the topic of the Blend SDK, solutions 1 and 2 can be achieved with zero code-behind if you make use of VisualStates and blend's EventTriggerBehavior and GoToStateAction to handle changing visual states on PointerEntered and PointerExited events.