开发者

WPF MVVM call ViewModel Save method on Window Close

开发者 https://www.devze.com 2023-01-04 18:43 出处:网络
I have figured out how to close Window from my ViewModel. Now I need to solve window close problem from the other side.

I have figured out how to close Window from my ViewModel.

Now I need to solve window close problem from the other side.

I need to trigger Save() method in my ViewModel when the user clicks window's close button.

I was thinking about binding Command property to Window's close event, but my ViewModel is related to the user control and in开发者_开发知识库 that case Close command will not be executed.

I was looking at this question as well Disposing WPF User Controls , but I'm afraid that putting Save method call in Dispose method is a little bit too late.

Is there any way to solve this problem?

Thank You very much!


If you always need to save on closing, why not call the Save() method from the Close() method in the ViewModel instead of from the View? Then just make sure that the window only closes from the ViewModel and not from the View itself. Something like (untested, but you get the idea)

public class SaveOnCloseViewModel
{
    public event Action RequestClose;
    ...
    public void Close()
    {
         Save();
         RequestClose();
    }
}

public class SaveOnCloseView
{
    private SaveOnCloseViewModel _vm;
    public SaveOnCloseView(SaveOnCloseViewModel vm)
    {
        _vm = vm;
        _vm.RequestClose += this.PerformClose;
        this.OnClosing += Window_Closing;
    }

    private bool _isClosing = false;
    private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
        if (!_isClosing)
        {
            e.Cancel = true;
            _vm.Close();
        }
    }

    private void PerformClose()
    {
        _isClosing = true;
        this.Close();
    }
}


I think the best solution for this would be to register the ViewModel at an event of your control which is also registered at the closed event of you window. This way you can also register other ViewModels at the windowClosed Event in the future to raise other save() Methods in other ViewModels

0

精彩评论

暂无评论...
验证码 换一张
取 消