简体   繁体   中英

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?

您是否尝试过将x强制转换为TabItem并在其上设置DataContext?

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

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