简体   繁体   中英

WPF MVVM TabControl DataContext is null

I'am trying to use a TabControl to display several views but I'm confused in correct setting of the DataContext for the views. I found in several discussions that the DataContext (here TemplateViewModel) will be automatically set to the view (here TemplateView), but this dosen't work for me.

MainWindow:

<TabControl Grid.Row="1" ItemsSource="{Binding Tabs}" SelectedIndex="{Binding   SelectedTab}">
        <TabControl.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding TabName}"/>
            </DataTemplate>
        </TabControl.ItemTemplate>
        <TabControl.ContentTemplate>
            <DataTemplate DataType="{x:Type models:TemplateViewModel}">
                <views:TemplateView />
            </DataTemplate>
        </TabControl.ContentTemplate>
    </TabControl>

MainWindowViewModel:

private ObservableCollection<ViewModelBase> _tabs;

public ObservableCollection<ViewModelBase> Tabs
    {
        get { return _tabs; }
        set { SetValue(ref _tabs, value, "Tabs"); }
    }

public SomeEvent()
    {
        TemplateViewModel model = new TemplateViewModel();
        model.TabName = value;
        Tabs.Add(model);
        SelectedTab = Tabs.IndexOf(model);
    }

On 'SomeEvent', I create a new TemplateViewModel and add it to the tabs collection of type ObservableCollection. The new tab with correct tabname and a TemplateView is displayed on MainView. The problem is, if I try to get the DataContext in TemplateView constructor the context is empty. Any idea?

public TemplateView()
    {
        InitializeComponent();

        TemplateViewModel model = (TemplateViewModel)DataContext;
    }

在MainWindow.xaml.cs中的构造函数中添加

this.DataContext = new MainWindowViewModel();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM