SergS
SergS

Reputation: 49

WPF & MVVM: CloseAction don't work

I write Application with WPF, MVVM, Prism and Unity. From of one Window I start secondary Window:

    public void ShowForm(IPrescriptionViewModel viewModel)
    {
        var view = new PrescriptionForm();
        view.SetDataContext(viewModel);
        view.ShowDialog();
    }

Method SetDataContext

    public void SetDataContext(IPrescriptionViewModel viewModel)
    {
        if (viewModel == null) return;
        DataContext = viewModel;
        if (viewModel.CloseAction == null)
            viewModel.CloseAction = new Action(this.Close);
    }

In BTMPrescriptionViewModel is a Property

   public Action CloseAction { get; set; }

and CloseCommandExecute

  public ICommand CloseCommand => new RelayCommand(CloseCommandExecute);

    private void CloseCommandExecute()
    {
        CloseAction();
    }

It works fine, but only once - the first. After closing the secondary window and again open it, it is no longer closed with command button, only with close button of the window. After closing and opening of the parent window, secondary window can I again close with command button, but again only once.

Upvotes: 1

Views: 418

Answers (1)

Peter Duniho
Peter Duniho

Reputation: 70691

Lacking a good Minimal, Complete, and Verifiable code example that reliably reproduces the problem, it's impossible to say for sure what the issue is. But, based on the code you posted here, it appears that you are creating a new window each time, but only setting the CloseAction property once.

Because the CloseAction delegate value you assign captures this to call the Close() method, it is always calling Close() on the first window you create, not any of the ones you create afterward.

Without a more complete code example, it's not clear what the best way for you to accomplish your goal is. But the basic issue would probably be solved if you just took out the null check and always assigned the value:

public void SetDataContext(IPrescriptionViewModel viewModel)
{
    if (viewModel == null) return;
    DataContext = viewModel;
    viewModel.CloseAction = this.Close;
}

Note that you also don't need to explicitly call the delegate constructor. The compiler has inference rules for dealing with delegate types, and simply referring to the method name is sufficient.

Upvotes: 2

Related Questions