UWP – Close a Flyout MVVM way with UWP XamlBehaviors

Using a Flyout control in an UWP app is super handy to show contextual actions, but somehow they aren’t very MVVM friendly.
It was easier during windows 8.1 days, but with UWP it’s a hassle.

I’ve seen many solutions on how to tackle this problem, but let you give me mine just to show some other angles.
I’m trying to use the new UWP XamlBehaviors that went Open Source a while back, for all the info take a look here https://github.com/Microsoft/XamlBehaviors.

So the setup, we have a page that has a button – that button will open a flyout. On this flyout we have another button that will trigger some long running process in MVVM ( it’s not in this demo 😛 ).
What we want to do is dismiss the flyout from our MVVM if the process is done.

Here is the XAML code

Some things to note… We are using a MVVM command through binding for the button that is shown on the flyout.
The other thing, is the DataTriggerBehavior! It’s one of the behavior types that is available through the XamlBehaviors and what it allows us to do is perform some action when some data element changes to a certain value.
Here we are monitoring the IsFlyoutClosed boolean of our MVVM ViewModel to see when it’s being set to True. If this happens, we’ll perform an action called CloseFlyoutAction.
This action is a custom one and it’s purpose is to close the current given Flyout, as shown in the code below.

And that’s it… only thing left to do is manipulate the boolean on the ViewModel when you want to close the flyout.

As always an example project is available on GitHub here… https://github.com/Depechie/UWPFlyoutCloseMVVM

4 thoughts on “UWP – Close a Flyout MVVM way with UWP XamlBehaviors”

  1. How to close the flyout?
    changing _isFlyoutClosed or IsFlyoutClosed to any value (true of false) doesnt close the flyout.

    Here are the close button command inside the flyout
    DelegateCommand _CloseFlyout;
    public DelegateCommand CloseFlyout
    => _CloseFlyout ?? (_CloseFlyout = new DelegateCommand(() =>
    {
    //_isFlyoutClosed = true;
    //_isFlyoutClosed = false;
    // IsFlyoutClosed = true;
    IsFlyoutClosed = false;
    }, () => true));

    Here are button flyout xaml

  2. Hey Syaiful did you check out the example on GitHub? ( link in blob ) it should just work if you set the IsFlyoutClosed to False – if the flyout is visually open.

Leave a Reply

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