什么是ViewModelLocator?与DataTemplates相比,它的优缺点是什么?

有人可以简要概述一下ViewModelLocator是什么,它如何工作以及与DataTemplates相比使用它的优点/缺点吗?

我曾尝试在Google上查找信息,但似乎有许多不同的实现方式,而没有关于它的含义以及使用它的利弊的详尽列表。


慕的地10843
浏览 1070回答 3
3回答

慕沐林林

我有一个视图模型定位器类。每个属性都将是我将在视图上分配的视图模型的实例。我可以检查代码是否在设计模式下运行或不使用DesignerProperties.GetIsInDesignMode。这使我可以在设计时使用模拟模型,并在运行应用程序时使用真实对象。public class ViewModelLocator{&nbsp; &nbsp; private DependencyObject dummy = new DependencyObject();&nbsp; &nbsp; public IMainViewModel MainViewModel&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; get&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (IsInDesignMode())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return new MockMainViewModel();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return MyIoC.Container.GetExportedValue<IMainViewModel>();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; // returns true if editing .xaml file in VS for example&nbsp; &nbsp; private bool IsInDesignMode()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return DesignerProperties.GetIsInDesignMode(dummy);&nbsp; &nbsp; }}要使用它,我可以将定位器添加到App.xaml资源中:xmlns:core="clr-namespace:MyViewModelLocatorNamespace"<Application.Resources>&nbsp; &nbsp; <core:ViewModelLocator x:Key="ViewModelLocator" /></Application.Resources>然后将您的视图(例如:MainView.xaml)连接到您的视图模型:<Window ...&nbsp; DataContext="{Binding Path=MainViewModel, Source={StaticResource ViewModelLocator}}">
打开App,查看更多内容
随时随地看视频慕课网APP