Data-binding PivotItem.Visibility : an helper

Posted by & filed under Dev', Sources.

A common quirk of Windows Phone’s Pivot control API is the lack of support of the Visibility property.
The property is held by the Pivot class, but toggling it to Visible or Collapsed does not change the visibility of the PivotItem. In fact the only way to hide a PivotItem is to remove it from its parent Items collection.

This is unfortunate because it is a common use-case to have a boolean property in your ViewModel that would be perfect to toggle the visibility of the PivotItem rather than writing code-behind or implementing a collection in your viewmodel for this scenario, polluting the viewmodel with unnecessary logic.

Here is a little extension class adding an attached property IsDisplayed to PivotItem that you can bind that will dynamically add/remove the PivotItem from its parent.

Source code :

How to use it :

Declare a boolean property in your ViewModel that triggers the NotifyPropertyChanged event on change (here with MVVM Light) :

#region public bool HasRelatedVideos
private bool _HasRelatedVideos;
public bool HasRelatedVideos
    return _HasRelatedVideos;
    _HasRelatedVideos = value;
    RaisePropertyChanged(() => HasRelatedVideos);

In your XAML file, declare a reference to the namespace of the PivotItemEx :


And finally declare and bind the attached property in the PivotItem :

<controls:PivotItem Header="{Binding l.star_related_videos, Source={StaticResource LocaleHelper}}"
		    uc:PivotItemEx.IsDisplayed="{Binding HasRelatedVideos}">

One Response to “Data-binding PivotItem.Visibility : an helper”

  1. Przemek

    Hi Pierre,
    Thanks for publish this code. It is very useful to me.
    I used your code in WP8 project and I have some problems with memory leaks. When I add your extension to view then GC are not collect this view.
    I try to find what is wrong. I see that method SubscribePivot isn’t used at all. Is this correct ?

    Thanks in advance for your explanation.