UWP: Drop down selector

Intro

Drop down selector can be used in scenarios when a user has to choose an option from a short list of values, but it doesn’t make any sense to show the whole list of values at a page. Can be useful to choose a sorting order or a filter:

There is no a similar control in UWP SDK. How to build a custom one? My intent in this article is to demonstrate how to do it with few lines of code, using based UI elements.

Base properties

Let’s name the new control DropDownButton and inherit it from Windows.UI.Xaml.Controls.Control. As usual, in the default constructor, it’s required to define DefaultStyleKey, in order to apply a style defined in Generics.xaml file:

DropDownButton needs at least ItemsSource, ItemTemplate and SelectedItem. These properties allow to bind data, apply custom view for a data item and use a selected value. And of course, they supposed to be dependency properties:

XAML template

The control template has the following parts:

  • To show a selected item, I use TextBlock;
  • ListView is to allow to choose a value;
  • And FontIcon, to highlight that the control is a kind of a selector.

The List part needs to be hosted in a popup, because we want to show it, when the user taps on the button. I use Flyout, not a popup. I define it as attached to the root Grid of the template:

There are two visual states defined in the template, PointerDown and PointerUp. They used to show when a user taps the control. I manage the animation with overridden OnPointerPressed and OnPointerReleased methods:

Codebehind

The core logic of the control is to show the list with available options, select an option, show the selected value an close the list on user tap outside of the control boundaries.

The easiest part is to open the list with items. To achieve that, I subscribe on Tapped event and call FlyoutBase.ShowAttachedFlyout in the event handler:

Another substantial part of any custom control is OnApplyTemplate method. This method is the entry point to subscribe for events of the elements, defined in the control template. It’s very important to have this method written correctly:

I want to update the button icon, when the flyout has been opened or closed. DownUnicode and UpUnicode are constants, which keep arrow down and up glyphes :

When a user selects an item, the list of the option should be hidden and selected value is shown. Selection changed event handler is also very simple:

Now the control is ready to use in your application:

The sources are here, fruitful coding!


Leave a Reply