Search code examples
c#wpfdatacontexttabitem

Set DataContext to a view in a TabItem


I have a ViewModel that handle a view called "WorkSpace". Now without going into non-useful details, to create a new tab inside my TabControl contained in this workspace, i raise an event with the viewmodel, that is implemented in the code behind of the view:

MainViewModel.ShowTab += OpenTab;
MainViewModel.FocusTab += FocusTab;

private void OpenTab(object sender, TabEventArgs e)
{
    // TabEventArgs are custom EventArgs who contain also a property called ChildViewModel
    object x = WorkAreaTabCtrl.Resources[e.name];
    WorkAreaTabCtrl.Items.Add(x);
    // do something here  
    WorkAreaTabCtrl.SelectedItem = x;
}

private void FocusTab(object sender, TabEventArgs e)
{
    object x = WorkAreaTabCtrl.Resources[e.name];
    WorkAreaTabCtrl.SelectedItem = x;
}

Inside the resources of my tab control, i defined different kind of tab items like the following:

<mh:MetroTabItem CloseButtonEnabled="True" x:Key="{x:Static res:Resources.LBL_1}" Header="{x:Static res:Resources.LBL_1}">
    <mh:MetroTabItem.Content>
         <path2view:myView1 x:Name="view1"/>
    </mh:MetroTabItem.Content>
</mh:MetroTabItem>

My problem is the following. How can i assign the ChildViewModel contained inside the TabEventArgs as DataContext for the TabItem i'm getting in the OpenTab method?


Solution

  • Did you try to cast x to TabItem and set the DataContext on it?

    ((TabItem) x).DataContext = e.ChildViewModel;