Home > C#, WinRT > Using a Behavior to open Attached Flyouts in Windows 8.1 Store apps

Using a Behavior to open Attached Flyouts in Windows 8.1 Store apps

17/12/2013

Some times ago we talk about new Flyout control in Windows 8.1. In that occasion, we showed how to use Flyout property of the Button control to create and automatically show the popup when the button is clicked.

We can attach a Flyout to any FrameworkElement, using the FlyoutBase.AttachedFlyout attached property. For example:

<Image Source="/Assets/Logo.scale-100.png"
       Height="100" Width="100">
    <FlyoutBase.AttachedFlyout>
        <Flyout>
            <StackPanel>
                <TextBlock Text="Awesome Flyout!" />
            </StackPanel>
        </Flyout>
    </FlyoutBase.AttachedFlyout>
</Image>

In this way, however, we must respond to an interaction on the FrameworkElement, such as the Tapped event, and explicitly open the Flyout in our code, using the ShowAttachedFlyout method.

Thanks to new Behavior SDK that comes with Windows 8.1, we can use an EventTriggerBehavior to automatically open the popup. Let’s see how do to that.

First of all, we need to add a reference to the Behavior SDK, that is available in the Windows > Extensions section of the Reference Manager dialog:

Reference Manager

Reference Manager

Then, let’s insert the required namespace declarations in our XAML page:

<Page
    ...
    xmlns:i="using:Microsoft.Xaml.Interactivity" 
    xmlns:core="using:Microsoft.Xaml.Interactions.Core"
    ...>

Now we can attach an EventTriggerBehavior to the Tapped event of the Image control:

<i:Interaction.Behaviors>
    <core:EventTriggerBehavior EventName="Tapped">
        ...
    </core:EventTriggerBehavior>
</i:Interaction.Behaviors>

Finally, we need to create an Action that is executed when the event trigger fires and that shows the control’s attached Flyout:

public class OpenFlyoutAction: DependencyObject, IAction
{
    public object Execute(object sender, object parameter)
    {
        FlyoutBase.ShowAttachedFlyout((FrameworkElement)sender);

        return null;
    }
}

An action is defined in a class that implements the Execute method of the IAction interface.

In conclusion, the complete XAML declaration looks like the following:

<Image Source="/Assets/Logo.scale-100.png"
       Height="100" Width="100">
    <FlyoutBase.AttachedFlyout>
        <Flyout>
            <StackPanel>
                <TextBlock Text="Awesome Flyout!" />
            </StackPanel>
        </Flyout>
    </FlyoutBase.AttachedFlyout>
    <i:Interaction.Behaviors>
        <core:EventTriggerBehavior EventName="Tapped">
            <local:OpenFlyoutAction />
        </core:EventTriggerBehavior>
    </i:Interaction.Behaviors>
</Image>

And that’s all: with this behavior, when we tap the Image, the attached Flyout will be automatically shown.

Categories: C#, WinRT
%d bloggers like this: