WPF MVVM: How to close a window

后端 未结 21 1811
后悔当初
后悔当初 2020-12-04 08:19

I have a Button that closes my window when it\'s clicked:


21条回答
  •  悲&欢浪女
    2020-12-04 08:58

    For small apps, I use my own Application Controller for showing, closing and disposing windows and DataContexts. It's a central point in UI of an application.

    It's something like this:

    //It is singleton, I will just post 2 methods and their invocations
    public void ShowNewWindow(Window window, object dataContext = null, bool dialog = true)
    {
        window.DataContext = dataContext;
        addToWindowRegistry(dataContext, window);
    
        if (dialog)
            window.ShowDialog();
        else
            window.Show();
    
    }
    
    public void CloseWindow(object dataContextSender)
    {
        var correspondingWindows = windowRegistry.Where(c => c.DataContext.Equals(dataContextSender)).ToList();
        foreach (var pair in correspondingWindows)
        {
            pair.Window.Close();              
        }
    }
    

    and their invocations from ViewModels:

    // Show new Window with DataContext
    ApplicationController.Instance.ShowNewWindow(
                    new ClientCardsWindow(),
                    new ClientCardsVM(),
                    false);
    
    // Close Current Window from viewModel
    ApplicationController.Instance.CloseWindow(this);
    

    Of course you can find some restrictions in my solution. Again: I use it for small projects, and it's enough. If you're interested, I can post full code here or somewhere else/

提交回复
热议问题