Search code examples
wpfmvvmtabcontroltabitem

How can I track the selected TabPage's DataContext from my ViewModel?


I have TabItem class:

 public class TabItem
{
    public string Header { get; set; }
    public IView Content { get; set; }
}

and in my model:

 public ObservableCollection<TabItem> Tabs
    {
        get { return _tabs; }
        set
        {
            if(_tabs!=value)
            {
                _tabs = value;
                RaisePropertyChanged("Tabs");
            }
        }
    }

    public TabItem CurrentTabItem
    {
        get { return _currentTabItem; }
        set
        {
            if (_currentTabItem != value)
            {
            }
            _currentTabItem = value;
            RaisePropertyChanged("CurrentTabItem");
        }
    }

In View i'm binding to ModelView:

<TabControl x:Name="shellTabControl" ItemsSource="{Binding Tabs}" 
            IsSynchronizedWithCurrentItem="True" SelectionChanged="ShellTabControlSelectionChanged">
    <TabControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Header}"/>
        </DataTemplate>
    </TabControl.ItemTemplate>
    <TabControl.ContentTemplate>
        <DataTemplate>
            <ContentPresenter Content="{Binding Content}"/>
        </DataTemplate>
    </TabControl.ContentTemplate>
</TabControl>

From view i want to change ViewModel's CurrentTabItem property:

 private void ShellTabControlSelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if(e.Source is TabItem)
        {
            var tabItem = e.Source as TabItem;
            ViewModel.CurrentTabItem = tabItem; //don't work
        }
    }

What is the best approach to convert TabControl's TabItem to my TabItem?


Solution

  • Maybe it is better to use SelectedItem="{Binding CurrentTabItem, Mode=TwoWay, UpdateSourceTrigget=PropertyChanged}"?