Click here to Skip to main content
15,893,904 members
Articles / Desktop Programming / WPF

Persist the Visual Tree when switching tabs in the WPF TabControl

Rate me:
Please Sign up or sign in to vote.
4.76/5 (14 votes)
16 Jun 2011CPOL5 min read 85.3K   3.1K   32  
Using attached behavior pattern to create a tab persist TabControl in WPF when ViewModel is used.
using System.Windows.Controls;
using System.Collections;

namespace PersistTabDemo.Behavior
{
    /// <summary>
    /// A wrapper to keep Tab.SelectedItem and PersistTabBehavior.SelectedItemProperty in sync
    /// </summary>
    public class PersistTabSelectedItemHandler
    {
        public TabControl Tab { get; private set; }

        public PersistTabSelectedItemHandler(TabControl tab)
        {
            Tab = tab;
            Tab.SelectionChanged += ChangeSelectionFromUi;
        }

        public void Dispose()
        {
            Tab.SelectionChanged -= ChangeSelectionFromUi;
            Tab = null;
        }

public void ChangeSelectionFromProperty()
{
    var selectedObject = Tab.GetValue(PersistTabBehavior.SelectedItemProperty);

    if (selectedObject == null)
    {
        Tab.SelectedItem = null;
        return;
    }

    foreach (TabItem tabItem in Tab.Items)
    {
        if (tabItem.DataContext == selectedObject)
        {
            if (!tabItem.IsSelected)
                tabItem.IsSelected = true;

            break;
        }
    }
}

private void ChangeSelectionFromUi(object sender, SelectionChangedEventArgs e)
{
    if (e.AddedItems.Count >= 1)
    {
        var selectedObject = e.AddedItems[0];

        var selectedItem = selectedObject as TabItem;

        if (selectedItem != null)
            SelectedItemProperty(selectedItem);
    }
}

private void SelectedItemProperty(TabItem selectedTabItem)
{
    var tabObjects = Tab.GetValue(PersistTabBehavior.ItemsSourceProperty) as IEnumerable;

    if (tabObjects == null)
        return;

    foreach (var tabObject in tabObjects)
    {
        if (tabObject == selectedTabItem.DataContext)
        {
            PersistTabBehavior.SetSelectedItem(Tab, tabObject);
            return;
        }
    }
}
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Fidelity
Hong Kong Hong Kong
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions