WPF (MVVM): Closing a view from Viewmodel?

后端 未结 11 1530
小鲜肉
小鲜肉 2020-12-12 16:23

Anybody come across a clever way of closing a view in a viewmodel using MVVM?

Maybe there is a way of using binding to signal the view (window) to close?

I w

11条回答
  •  轮回少年
    2020-12-12 16:44

    I used to use the dialogcloser attached behavior, but i find the below solution easier where I can use it. The sample below takes an example of a close button on the window for simplicity.

    pass the window as the command parameter.

    in the button xaml for the view:

    CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}"
    

    in the command execute method in the view model:

    if (parameter is System.Windows.Window)
    {
        (parameter as System.Windows.Window).Close();
    }
    

提交回复
热议问题