我是 WPF MVVM C# 的初学者程序员。当用户安装我的应用程序时,他将遵循教程。因此,对于教程的每个“屏幕”,我创建了一个窗口。在每个屏幕上,我都有一个后退按钮。
所以,我对打开新窗口并返回上一个窗口的良好做法感到非常困惑。做这个的最好方式是什么?目前,我正在做:
第一个窗口(下一步按钮)- ViewModel1
<Button Command="{Binding NextWindowCommand}" >
public void NextWindow(object parameter)
{
var newWindow = new Window2();
newWindow.Show();
newWindow.DataContext = new ViewModel2();
CloseWindow();
}
Run Code Online (Sandbox Code Playgroud)
第二个窗口(后退按钮)ViewModel2
<Button Command="{Binding BackWindowCommand}" >
public void Back(object parameter)
{
var backWindow = new Window1();
backWindow.Show();
backWindow.DataContext = new ViewModel1();
CloseWindow();
}
Run Code Online (Sandbox Code Playgroud)
关闭窗口方法(我的ViewModelBase):
public bool? CloseWindowFlag
{
get { return _CloseWindowFlag; }
set
{
_CloseWindowFlag = value;
RaisePropertyChanged("CloseWindowFlag");
}
}
public virtual void CloseWindow(bool? result = true)
{
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
{
CloseWindowFlag = CloseWindowFlag == null
? true
: !CloseWindowFlag;
}));
}
Run Code Online (Sandbox Code Playgroud)
DataTemplates如果您想根据以下情况动态切换视图,则适合使用ViewModel:
<Window>
<Window.Resources>
<DataTemplate DataType="{x:Type ViewModelA}">
<localControls:ViewAUserControl/>
</DataTemplate>
<DataTemplate DataType="{x:Type ViewModelB}">
<localControls:ViewBUserControl/>
</DataTemplate>
<Window.Resources>
<ContentPresenter Content="{Binding CurrentView}"/>
</Window>
Run Code Online (Sandbox Code Playgroud)
如果Window.DataContext是 的实例ViewModelA,则将ViewA显示,并且Window.DataContext是 的实例ViewModelB,则将ViewB显示。
我见过和读过的最好的例子是 Rachel Lim 制作的。请参阅示例。
我强烈建议你关注Prism框架。这个教程非常好。
更新:
让我举一个例子,可以看出你应该把它放在哪里DataTemplates:
<Window x:Class="SimpleMVVMExample.ApplicationView"
...The code omitted for the brevity...
Title="Simple MVVM Example with Navigation" Height="350" Width="525">
<Window.Resources>
<DataTemplate DataType="{x:Type ViewModelA}">
<localControls:ViewAUserControl/>
</DataTemplate>
<DataTemplate DataType="{x:Type ViewModelB}">
<localControls:ViewBUserControl/>
</DataTemplate>
</Window.Resources>
<DockPanel>
<Border DockPanel.Dock="Left" BorderBrush="Black" BorderThickness="0,0,1,0">
<ItemsControl ItemsSource="{Binding ListOfViewModels}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content="{Binding Name}"
Command="{Binding DataContext.ChangePageCommand, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
CommandParameter="{Binding }"
Margin="2,5"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Border>
<ContentControl Content="{Binding CurrentDataTemplateViewModel}" />
</DockPanel>
</Window>
Run Code Online (Sandbox Code Playgroud)
要查看完整的工作示例,请参阅 Rachel Lim 的页面。
要下载示例,请单击此处。