c# - 在 MVVMLight 中关于 ViewModelLocator 正确使用 MEF

标签 c# mvvm mef mvvm-light

我正在尝试使用 MEF 和 MVVMLight 来构建我的应用程序。

我现在已经成功地将一些东西连接在一起,并且可以成功导入,但在这个过程中,我似乎完全错过了 ViewModelLocator,我只是想知道如何将 MEF 与 ViewModelLocator 一起正确使用,也许您是否真的需要一个还是我的设计出了问题?

因此,在我的 App.xaml 中,我禁用startupUri,并在 App.xaml.cs 中执行以下操作:

[Import("MainWindow", typeof(Window))]
public new Window MainWindow
{
    get { return base.MainWindow; }
    set { base.MainWindow = value; }
}

protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);
    // Load catalog in normal way
    ...
    MainWindow.Show();
}

我的主窗口代码是这样的:

[Export("MainWindow", typeof(Window))]
public partial class MainWindow : Window
{
    [ImportingConstructor]
    public MainWindow([Import("MainViewModel")] MainViewModel vm)
    {
        InitializeComponent();
        DataContext = vm;
    }
}

最后我的 ViewModel 是这样的:

[Export("MainViewModel", typeof(MainViewModel))]
public class MainViewModel : ViewModelBase, IPartImportsSatisfiedNotification
{
    // I do some MEF imports here also
}

但是我正确的做法是什么,或者有更明智的方法吗?我真的可以忽略 ViewModelLocator 吗?

最佳答案

我不知道这是否是“正确”的方法,但我也不直接使用 ViewModelLocator。我通常使用 Prism,并使用 Bootstrap 方法实现 MEF,但我通过这样做将我的 View 连接到它们的 View 模型:

[Import]
public TransactionViewModel ViewModel
{
    get { return (TransactionViewModel)DataContext; }
    set { DataContext = value; }
}

这是代表我的 View 代码隐藏中的 ViewModel 的属性。这样我就不会对我的窗口的构造函数做任何事情。在您的示例中,您不再有默认构造函数(至少您显示的)。虽然这在这里可能不是问题,但如果您养成了这样做的习惯,然后需要让 WPF 为您实例化 View (例如在数据上下文中),您就会遇到问题。

但除此之外,你所做的事情对我来说看起来很标准。您可能还想查看 Prism 的 MEF 实现。 Prism 还包括 Unity,它可以实现不同的目的,并且还具有其他优点,可以使创建应用程序框架变得更加容易。

关于c# - 在 MVVMLight 中关于 ViewModelLocator 正确使用 MEF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14641995/

相关文章:

wpf - 将元素焦点与附加属性绑定(bind)?

c# - MEF 属性总是返回 Null

c# - MVC 5 'Cannot create an instance of an interface' 中的接口(interface)问题

c# - 表单验证: Determine why ticket is invalid

c# - UWP-如何通过右键单击或右击而没有选择Listviewitem来获取ListViewItem值?

wpf - 使用 MVVM 构建应用程序

c# - clr 的原因! PerfView CPU 堆栈中的 JIT_New

c# - 如何在C#中隐藏打印弹出窗口?

c# - 具有 ImportMany 和 ExportMetadata 的 MEF

c# - 如何在应用程序运行时发现新的 MEF 部件?