【发布时间】:2016-11-27 07:00:56
【问题描述】:
我在 WPF 项目中使用 Prism 和 Unity IOC-Container。对于我所有的其他视图,我每个视图只使用一个 ViewModel。因为这个视图应该是数据输入和输出的掩码,所以我想使用两个视图模型。
对于当前导航到视图,我使用以下代码:
_regionManager.RequestNavigate(RegionNames.ContentRegionName, typeof(Events).ToString());`
我的观点背后的代码:
public partial class Events : UserControl
{
public Events(EventsViewModel viewModel)
{
InitializeComponent();
}
}
其中一个 ViewModel:
public class EventsViewModel : BindableBase
{
public EventsViewModel()
{
// Some Code
}
// Some other Code
}
我听说过 ViewModel Discovery,您可以在其中为 View 的构造函数提供一个接口,而不是一个实际的 ViewModel。但是我只能找到这么多的信息。
// Example of such a Method
public Events(IViewModel viewModel)
{
InitializeComponent();
DataContext = viewModel
}
public Interface IViewModel
{
}
我现在的问题是:我如何导航到视图并告诉它应该作为 DataContext 获得的 ViewModel?我对编程比较陌生,MVVM 模式和英语不是我的母语,所以也许我错过了一些信息。如果有人对此有答案,我会很高兴。提前致谢。
编辑:解决方法
我想出了一个适合我的解决方法。我使用了ViewModelLocationProvider中的SetDefaultViewTypeToViewModelTypeResolver()方法并对其进行了自定义。
// Bootstrapper.cs
protected override void InitializeShell()
{
var window = (MainWindow)this.Shell;
Application.Current.MainWindow = window;
// Calling the method
ViewModelLocationProvider.SetDefaultViewTypeToViewModelTypeResolver(ResolveViewModel);
var regionManager = Container.Resolve<IRegionManager>();
window._regionManager = regionManager;
globalRegionManager = regionManager;
regionManager.RegisterViewWithRegion(RegionNames.ContentRegionName, typeof(StartScreen));
regionManager.RegisterViewWithRegion(RegionNames.ContentRegionName, typeof(Stock));
window.Show();
}
// Property for handing over the desired ViewModel
public static Type DynamicViewModel { private get; set; }
private Type ResolveViewModel (Type viewType)
{
string _viewModel = null;
var name = viewType.FullName.Replace(".Views.", ".ViewModels.");
if (DynamicViewModel != null)
_viewModel = DynamicViewModel.ToString();
else
_viewModel = $"{name}ViewModel";
var fullName = IntrospectionExtensions.GetTypeInfo(viewType).Assembly.FullName;
var typeString = string.Format(CultureInfo.InvariantCulture, $"{_viewModel}, {fullName}");
DynamicViewModel = null;
return Type.GetType(typeString);
}
然后当我想导航的时候,我提前交出ViewModel。
private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
{
Bootstrapper.DynamicViewModel = typeof(EventsViewModel);
_regionManager.RequestNavigate(RegionNames.ContentRegionName, typeof(Events).ToString());
}
有点棘手,但它似乎在没有任何异常的情况下工作。
如果有更清洁的方式,我总是很乐意在这里。 :)
【问题讨论】:
-
为什么不导航到视图模型并将视图解析为数据模板?
标签: c# mvvm unity-container prism ioc-container