WPF MVVM: How to close a window

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

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


21条回答
  •  星月不相逢
    2020-12-04 08:37

    I just completed a blog post on this very topic. In a nutshell, add an Action property to your ViewModel with get and set accessors. Then define the Action from your View constructor. Finally, invoke your action in the bound command that should close the window.

    In the ViewModel:

    public Action CloseAction  { get; set;}
    

    and in the View constructor:

    private View()
    {
        InitializeComponent();
        ViewModel vm = new ViewModel();
        this.DataContext = vm;
        if ( vm.CloseAction == null )
            vm.CloseAction = new Action(this.Close);
    }
    

    Finally, in whatever bound command that should close the window, we can simply invoke

    CloseAction(); // Calls Close() method of the View
    

    This worked for me, seemed like a fairly elegant solution, and saved me a bunch of coding.

提交回复
热议问题