C# 使用 MVVM - 困难的行为

C# using MVVM - Difficult Behavior

在花了几个小时(也许几天)努力解决问题后,我决定相信您的知识。我想实现这个行为(蓝色):

因此,在 loginButton 中,我触发了一个在 loginViewModel 中处理的命令,在此处理程序中,我对网络服务进行了一些验证,并且使用该答案,我想打开一个新的 Window 发送一个用户 (class)。我怎样才能做到这一点?

我试过消息传递,我试过很多东西。在后面的代码中,我想使用 MVVM 架构来做这样的事情。

LoginView 代码隐藏

 button_OnClick(){
// Checking stuff
    var u = //from the server;
    PrincipalView pv = new PrincipalView(u);
    pv.Show();
    this.Close()
}

PrincipalView 代码隐藏中:

public PrincipalView(User u){
        // Yey, I have the user
  }

我是通过使用自定义 window 服务 class 完成的,如下所示:

 class WindowsService
{
    private static LoginWindow loginWindow{ get; set; }

    private static UserWindow UserWindow{ get; set; }

    public void ShowLoginWindow(LoginViewModel loginViewModel)
    {
        LoginWindow = new LoginWindow 
        {
            DataContext = loginViewModel
        };
        LoginWindow.Show();
    }
    public void ShowUserWindow(UserViewModel userViewModel)
    {
        UserWindow = new UserWindow 
        {
            DataContext = userViewModel
        };

        LoginWindow .Hide();
        UserWindow.Show();
    }
}

因此,您在 LoginViewModel 中声明了 WindowsService 的一个实例,当您的逻辑找到用户时,您就创建了 WindowsService 的一个实例=26=]UserViewModel 并调用 windowsService.ShowUserWindow(userViewModel)。为了正确使用它,您必须像这样修改 App.xaml.cs 文件

public partial class App : Application
{
    private void App_OnStartup(object sender, StartupEventArgs e)
    {
        var loginViewModel = new LoginViewModel();
        loginViewModel.StartLoginWindowService();
    }
}

方法 StartLoginWindowService() 可能如下所示:

public void StartLoginWindowService()
    {
        WindowsService.ShowLoginWindow(this);
    }

如果有帮助请告诉我

说明在何处创建 UserWindowViemodel

假设您的 loginViewmodel 中有以下方法

public void Loging(string name, string pass){
  var isAllowed(name, pass); //Check if user exists and if pass is correct
  if(!isAllowed) return; //we return if user is invalid
  var wService = new WindowsService();
  var myUser = new UserWindowViewModel(name){
    //you set all proeperties you need here
  }
  wService.ShowUserWindow(myUser);
}

您可能需要一个服务,当您向它传递一个 ViewModel 时,它会打开一个 window。

基本上,您将拥有一个 ViewLocator,当您给它一个 ViewModel 时,它会为您找到指定的视图。 UIService 具有 ShowShowDialog 等方法,您可以向其传递任何 ViewModel。然后,这些方法将打开已注册的视图,并为新创建的 ViewModel 分配一个新的 UIService。

我在中详细描述了这个过程。