如何从ViewModel跟踪选定的TabPage的DataContext?

时间:2011-11-16 06:30:53

标签: wpf mvvm tabcontrol tabitem

我有TabItem类:

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

在我的模特中:

 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");
        }
    }

在View中我绑定到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>

从视图中我想更改ViewModel的CurrentTabItem属性:

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

将TabControl的TabItem转换为我的TabItem的最佳方法是什么?

2 个答案:

答案 0 :(得分:1)

使用SelectedItem =“{Binding CurrentTabItem,Mode = TwoWay,UpdateSourceTrigget = PropertyChanged}”可能更好吗?

答案 1 :(得分:0)

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

这将为您提供所选的TabItem .......

同时更改自定义“TabItem”的名称令人困惑;)