Multiple Flyout Templates for ComboBox and Changing the Header

Multiple Flyout Templates for ComboBox and Changing the Header

Following my previous post Breaking apart the Windows Phone 8.1 ComboBox Style and Colors a reader asked me:
– How to vary the flyout template so that each combobox could have a different appearance
– Change the header on the flyout from the default “CHOOSE AN ITEM”

The ComboBox uses the default style for the ListPickerFlyoutPresenter which means that in order to vary the template for each ComboBox you need to change the default style. Luckily you can do this in code. Take the following XAML which declares two Styles based on the same base style for the ListPickerFlyoutPresenter with the background color varying.
<Style
    x_Key=”PurpleBackgroundListPickerFlyoutPresenter”
    TargetType=”ListPickerFlyoutPresenter”
    BasedOn=”{StaticResource CustomListPickerFlyoutPresenter}”>
    <Setter
        Property=”Background”
        Value=”Purple” />
</Style>
<Style
    x_Key=”GreenBackgroundListPickerFlyoutPresenter”
    TargetType=”ListPickerFlyoutPresenter”
    BasedOn=”{StaticResource CustomListPickerFlyoutPresenter}”>
    <Setter
        Property=”Background”
        Value=”Green” />
</Style>

In order to switch between templates you just need to change the default template using the type as the key:

private void PurpleClick(object sender, RoutedEventArgs e) {
    var purple = Application.Current.Resources[“PurpleBackgroundListPickerFlyoutPresenter”];
    Application.Current.Resources[typeof (ListPickerFlyoutPresenter)] = purple;
}

private void GreenClick(object sender, RoutedEventArgs e) {
    var green = Application.Current.Resources[“GreenBackgroundListPickerFlyoutPresenter”];
    Application.Current.Resources[typeof(ListPickerFlyoutPresenter)] = green;
}

The second part is a little harder to track down because it doesn’t appear that the text “CHOOSE AN ITEM” is set anywhere but it’s being set on the TitlePresenter TextBlock in the ListPickerFlyoutPresenter template. Often by removing named items in the default template you can raise an internal exception. Luckily in this case you can simply remove the TitlePresenter element and replace it with a similar TextBlock containing the header you want. Setting the TitlePresenter to Collapsed doesn’t work as it’s set to Visible by the ComboBox so you actually need to either remove the item or set the Opacity to 0.

Leave a Reply

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