【发布时间】:2016-09-02 09:52:18
【问题描述】:
我正在使用 MVVM 模式构建我的第一个 WPF 应用程序。
应用程序以包含登录按钮的登录视图开始。
当我点击登录按钮时,它会在 LoginViewModel 中执行 ICommand,如果登录成功,则会从服务器获取响应。
(我正在使用用户凭据构建基于 WCF 和 WPF 的聊天)
*我想要实现的是:如果登录成功,会切换到SignUp视图
(我知道它没有任何意义,但它只是为了测试视图切换)
到目前为止,我一直在阅读有关通过按钮的导航。正如你所理解的,这不是我的目标。
我想要的只是验证用户,然后加载聊天视图(我还没有,所以这就是为什么我提到没有任何意义的注册视图)
我有一个 主窗口 和 Xaml 代码,其中仅包含带有网格的 Content Control 以便切换视图:
<Grid>
<ContentControl Name="mainWindowContent" Content="{Binding CurrentView}"></ContentControl>
</Grid>
主窗口viewModel是MainWinowViewModel,它只包含一个名为CurrentView的ViewModelBase和切换的ICommands CurrentView 每次到不同的 ViewModel:
public class MainWindowViewModel
{
// simplified properties
public ViewModelBase CurrentView { get; set; }
public ICommand ViewLoginCommand { get; }
public ICommand ViewSignUpCommand{ get; }
public MainWindowViewModel()
{
ViewLoginCommand =new MyCommand(SetCurrentViewToLoginViewModel);
ViewSignUpCommand = new MyCommand(SetCurrentViewToSignUpViewModel);
CurrentView = new LoginViewModel();
}
private void SetCurrentViewToLoginViewModel()
{
CurrentView = new LoginViewModel();
}
private void SetCurrentViewToSignUpViewModel()
{
CurrentView = new SignUpViewModel();
}
}
我将 DataContext 分配给 MainWindow.CS
中的 MainWindowViewModel所有正确的模板都在 App.xaml 文件中,该文件显示了每个 ViewModel 的视图:
<Application.Resources>
<DataTemplate DataType="{x:Type local:LoginViewModel}">
<Views:LoginView />
</DataTemplate>
<DataTemplate DataType="{x:Type local:SignUpViewModel}">
<Views:SignUpView />
</DataTemplate>
</Application.Resources>
再次,我希望主窗口一次只显示一个视图,而没有导航视图。
我的问题:
如何在登录成功后将 CurrentView 更改为 SignUpViewModel。
我错过了什么吗?我的架构正确吗?你会做点不一样的吗?
在我看来,它只能在 LoginViewModel 内以某种方式发生,登录成功后,它将执行 ViewSignUpCommand 在 DataContext 中没有意义并且不起作用。
我看不出它是如何结合在一起的。感谢您的帮助!
顺便说一句,请原谅我的英语。如果需要其他任何内容(细节等)才能看到全局,请同时通知我。
【问题讨论】:
-
是的,您必须在需要时执行命令从 ViewModel 切换视图:根据您的要求,“登录成功后”。为什么没有意义?你没有展示这一点的实现,所以你不能声称它不起作用......