0

Background : I have a Window having a tab control with each tab having a separate UserControl. I have followed MVVM for each user control and MEF to obtain the controls to be displayed in the tab at runtime. This is my implementation

interface ITabControl
{
} 

[Export(typeof(UserControl1ViewModel))]
class UserControl1ViewModel
{

}

class UserControl1: ITabControl
{
   [Import(typeof(UserControl1ViewModel))]
   public UserControl1ViewModel ViewModel
   {
        get { return this.DataContext as UserControl1ViewModel; }
        set { this.DataContext = value; }
   }
}

//Other user controls have similar implementation

public class WindowViewModel
{
    //Import all type of ITabControl and set the TabCollection(bound to ItemSource property of tab control)
}

Problem : Now I have some validations to be done on a particular set of tabs based on the user action in the main window. So I have used another interface called IConfiguration which is implemented by some user control ViewModels.

interface IConfiguration
{
   public void Action1();
   public void Action2();
   ------------------- (many more)
} 

public class Window
{
   //Import all type of IConfiguration and call Action1/Action2 for all these types based on user actions. 
}

Now, if an error is encountered during validation (IConfigure actions impelemented in different ViewModels) in any of the above tabs, I need to set the SelectedTabItem property of the tab control to that particular tab. Since these actions are implemeted in the ViewModel, I'm unable to obtain the UserControl to set the SelectedTabItem property. How do I achieve this?

PS: I know I can achieve this by implementing IConfiguration in UserControl view instead of ViewModel this way

public class UserControl1 : IConfiguration
{ 
  public void Action1
  {
    this.ViewModel.Action1();
  }
  public void Action2
  {
    this.ViewModel.Action2();
  }
 //--------
} 

I wonder if there is a better way to achieve this.

nan
  • 585
  • 2
  • 9
  • 22

1 Answers1

0

Use an overarching viewmodel which contains a collection of ViewModels (one per tab) and a property which represents the active tab.

When you need to swap the active tab you can do it in the viewmodel just by updating the property that represents the active tab. This answer here shows you how to bind the active tab in the TabControl.

Community
  • 1
  • 1
benPearce
  • 37,735
  • 14
  • 62
  • 96