views:

65

answers:

2

Hello,

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 http://stackoverflow.com/questions/502761/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!

+1  A: 

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

KroaX
This worked for me....Thanks :)
Daniil Harik
+2  A: 

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();
    }
}

odd parity