使用MVVM模式的WPF swtich视图没有导航视图

时间:2016-09-02 09:52:18

标签: c# wpf wcf mvvm binding

我正在使用MVVM模式构建我的第一个WPF应用程序。

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

当我点击登录按钮时,它会执行 LoginViewModel 中的 ICommand ,如果登录成功,它会从服务器获得响应。

(我正在使用用户凭据构建基于WCF和WPF的聊天)

*我想要达到的目标是:如果登录成功,它将切换到 SignUp视图

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

到目前为止,我一直在通过按钮阅读导航。这不是我理解的目标。

我想要的只是验证用户,然后加载聊天视图(我还没有,所以这就是为什么我提到了没有任何意义的SignUp View)

我有一个主窗口 Xaml代码,其中只包含带有网格的内容控件以便切换视图:

   <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中没有意义且不起作用。

我无法看到它如何将它们联系在一起。谢谢你的帮助!

顺便说一句,请原谅我的英语。如果需要其他任何东西(细节等等)以便了解整体情况,请通知我。

1 个答案:

答案 0 :(得分: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/为例。