c# – 创建没有MVVM框架的子窗口
发布时间:2020-12-15 22:25:10 所属栏目:百科 来源:网络整理
导读:我正在编写一个小应用程序,同时在 WPF中学习MVVM. 只要我继续使用一个窗口,一切都很简单. 现在我想用特定的ViewModel打开一个新窗口. 我有一个主ViewModel,它包含一个应该打开一个新的Window / ViewModel的Command,以及一个Parameter. 为了以MVVM方式执行此
我正在编写一个小应用程序,同时在
WPF中学习MVVM.
只要我继续使用一个窗口,一切都很简单. 我有一个主ViewModel,它包含一个应该打开一个新的Window / ViewModel的Command,以及一个Parameter. 为了以MVVM方式执行此操作,我创建了一个NavigationService,我想这样调用: public MainWindowViewModel() { DetailsCommand = new DelegateCommand(Details); } public void Details() { SessionsViewModel sessions = new SessionsViewModel(); _NavigationService.CreateWindow(sessions); } 我注意到可以在XAML中“绑定”Views和ViewModel,如下所示: <Application x:Class="TimeTracker.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TimeTracker" xmlns:vm="clr-namespace:TimeTracker.ViewModels" xmlns:vw="clr-namespace:TimeTracker.Views" StartupUri="Views/MainWindow.xaml"> <Application.Resources> <ResourceDictionary> <DataTemplate DataType="{x:Type vm:MainWindowViewModel}"> <vw:MainWindow /> </DataTemplate> <DataTemplate DataType="{x:Type vm:SessionsViewModel}"> <vw:Sessions /> </DataTemplate> </ResourceDictionary> </Application.Resources> </Application> <Window x:Class="TimeTracker.Views.Sessions" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:TimeTracker.Views" xmlns:vm="clr-namespace:TimeTracker.ViewModels" mc:Ignorable="d" Title="Sessions" Height="300" Width="300"> <Window.DataContext> <vm:SessionsViewModel/> </Window.DataContext> <Grid> <TextBlock Text="Hallo" /> </Grid> </Window> 我遇到的问题是我不知道如何在NavigationService中使用此ResourceDictionary,因此我只能使用其ViewModel创建一个新的Window. class NavigationService { public void CreateWindow(IViewModel viewModel) { //How do I create a new Window using the ResourceDictionary? } } 解决方法
确保在新窗口中有ContentControl或ContentPresenter,以便可以显示ViewModel.接下来,确保资源字典在范围内.将它放在Application.Resources中将使其全局化并保证WPF可以找到DataTemplate.
另外,不要在DataTemplate中使用Window类作为视图.使用子窗口面板(例如,Grid,StackPanel等). 我这样做: <blah:MyChildWindow> <ContentControl Content={Binding DataContext}/> </blah:MyChildWindow> And in Application.Resources: <DataTemplate DataType={x:Type blah:MyViewModel}> <blah:MyChildWindow/> </DataTemplate> 顺便说一句 – 使用DataTemplates你正在尝试的方式是一个很好的模式. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
热点阅读