views:

44

answers:

1

I can add & remove tabs similar to the famous MSDN article. Basically a ObservableCollection<TabViewModels>. And I add tabs like _tabs.Add(new TabViewModel()) but the newest tab is not focused. I want to focus it. How do I do it?

1 way to do it

since i have a view source for my observable collection, I can do the below... another option will be @vorrtex method

public void OnTabsChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    if (e.NewItems != null && e.NewItems.Count > 0)
        foreach (TabViewModel tab in e.NewItems)
        {
            tab.CloseRequested += OnCloseRequested;
            _tabsViewSource.MoveCurrentTo(tab);
        }
    if (e.OldItems != null && e.OldItems.Count > 0)
        foreach (TabViewModel tab in e.OldItems)
            tab.CloseRequested -= OnCloseRequested;
}
+5  A: 

Use SelectedItem:

    public ObservableCollection<TabViewModel> Pages { get; set; }

    private TabViewModel currentPage;

    public TabViewModel CurrentPage
    {
        get { return currentPage; }
        set
        {
            currentPage = value;
            OnPropertyChanged("CurrentPage");
        }
    }

    public void AddPage()
    {
        var page = new TabViewModel();
        this.Pages.Add(page);
        this.CurrentPage = page;
    }

XAML:

<TabControl ItemsSource="{Binding Pages}" SelectedItem="{Binding CurrentPage, Mode=TwoWay}" />
vorrtex
I also found another way to do it, in my update since i am using `CollectionViewSource`. That way, I won't need yet another property
jiewmeng