2016-09-02 131 views
1

我使用MVVM模式构建我的第一个WPF应用程序。使用MVVM模式的WPF swtich视图无导航视图

该应用程序以登录视图开头,其中包含一个登录按钮。

当我点击登录按钮,它执行的ICommandLoginViewModel如果登录succeded是从服务器获得响应。

(我建立一个基于WCF和WPF使用用户凭据聊天)

*我想实现的是:如果登录成功,则会切换到注册视图

(我知道这没有任何意义,但它只是用于测试视图切换)

到目前为止,我一直在通过按钮念叨导航。你的理解并不是我的目标。

所有我想要的是验证用户,然后,装入聊天视图(这我没有还,所以这就是为什么我mentiond在注册查看犯规任何意义)

我有一个主窗口XAML代码仅包含内容控制为了切换视图withing网格:

<Grid> 
    <ContentControl Name="mainWindowContent" Content="{Binding CurrentView}"></ContentControl> 
    </Grid> 

主窗口视图模型是MainWinowViewModel仅包含一个ViewModelBase命名CurrentView个ICommand使得每次CurrentView切换到不同的视图模型:

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到MainWindowViewModel在MainWindow.CS

所有正确的模板放在App.xaml文件中,瓦特为每个视图模型:

<Application.Resources> 

    <DataTemplate DataType="{x:Type local:LoginViewModel}"> 
     <Views:LoginView /> 
    </DataTemplate> 
    <DataTemplate DataType="{x:Type local:SignUpViewModel}"> 
     <Views:SignUpView /> 
    </DataTemplate> 

</Application.Resources> 

同样,我想主窗口到在一个时间仅呈现1视图不具有导航视图一边。

我的问题:

我如何作出这样一旦登录成功,将CurrentView将变为SignUpViewModel。

我错过了什么吗?我的架构是否正确?你会做任何不同的事情吗?

我看到它的方式,它只能happpen如果不知何故LoginViewModel内,登录成功后,它会在DataContext的执行ViewSignUpCommand 这没有意义并不起作用。

我看不出它是如何结合在一起的。 Thx在前面为您提供帮助!

顺便说一句,请原谅我的英语。如果需要其他内容(细节等)以便看到大图,请通知我。

+0

是的,您需要执行该命令以在需要时从ViewModel切换视图:按照您的要求“在登录成功后”。为什么它没有意义?你没有展示这一点的实现,所以你不能声称它不工作...... –

回答

1

您正在通过一个命令更改CurrentView,但视图并不知道有关更改而未通知。这是通过实现INotifyPropertyChanged接口完成的。

我通常从ViewModelBase派生每个viewmodel类。 ViewModelBase实现INotifyPropertyChanged。在线查看示例以了解此类实现。

您应该结束了,像这样:

public class MainWindowViewModel:ViewModelBase 
{ 
     private ViewModelBase _CurrentView; //ViewModelBase or any common class,or interface of both types of views. 
     private ViewModelBase CurrentView 
     { 
      get 
      { 
       return _CurrentView; 
      } 
      set 
      { 
       if(_CurrentView != value) 
       { 
        _CurrentView = value; 
        OnPropertyChanged(); 
       } 
      } 
     } 
} 

,如果你不想用可重复使用的ViewModelBase类打扰,那么你可以简单地实现对MainWindowViewModel INotifyPropertyChanged的。

http://www.c-sharpcorner.com/uploadfile/0b73e1/mvvm-model-view-viewmodel-introduction-part-3/为例。