【问题标题】:Implementing interfaces in View and ViewModels using MEF and MVVM使用 MEF 和 MVVM 在 View 和 ViewModels 中实现接口
【发布时间】:2017-06-08 20:38:28
【问题描述】:

背景:我有一个窗口有一个选项卡控件,每个选项卡都有一个单独的用户控件。我为每个用户控件和 MEF 遵循了 MVVM,以获取要在运行时显示在选项卡中的控件。这是我的实现

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

问题:现在我要根据主窗口中的用户操作对一组特定的选项卡进行一些验证。所以我使用了另一个名为 IConfiguration 的接口,它由 some 用户控件 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. 
}

现在,如果在上述任何选项卡中的验证过程中遇到错误(不同 ViewModel 中的 IConfigure 操作),我需要将选项卡控件的 SelectedTabItem 属性设置为该特定选项卡。由于这些操作是在 ViewModel 中实现的,因此我无法获取 UserControl 来设置 SelectedTabItem 属性。我如何实现这一目标?

PS:我知道我可以通过在 UserControl 视图而不是 ViewModel 中实现 IConfiguration 来实现这一点

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

我想知道是否有更好的方法来实现这一点。

【问题讨论】:

    标签: c# wpf mvvm mef


    【解决方案1】:

    使用包含 ViewModel 集合(每个选项卡一个)和一个表示活动选项卡的属性的总体视图模型。

    当您需要交换活动选项卡时,您可以在视图模型中通过更新表示活动选项卡的属性来完成。这个答案here 向您展示了如何在 TabControl 中绑定活动选项卡。

    【讨论】:

      猜你喜欢
      • 2010-10-03
      • 1970-01-01
      • 1970-01-01
      • 2011-01-31
      • 2014-08-28
      • 1970-01-01
      • 1970-01-01
      • 2013-03-12
      • 1970-01-01
      相关资源
      最近更新 更多