0

I would like to open a dialog in my application and I would like to close the view when a property in the view model is changed.

So I am thinking in ths way:

1.- In my view.axml.cs (code behind) I have a method named close() that executes the close method of the view.

2.- In my view model I have a property called ViewModelClosing, a bool.

3.- The view, in some way, I don't know really how, needs to bind the property of the view model and execute the method in the code behind when the property changed.

Is it possible to do that?

PaulG
  • 13,871
  • 9
  • 56
  • 78
Álvaro García
  • 18,114
  • 30
  • 102
  • 193

1 Answers1

2

Álvaro García

The simplest and IMO the best way to do this is to accept an ICommand in your ViewModel from the controller.

Since ViewModel should not be dependent on View or for that matter ViewController, the follwoing solution uses dependency injection / inversion of control.

The DelegateCommand (aka RelayCommand) is a wrapper for ICommand

I have kept the code to its minimum to focus on the solution.

public class ViewController
{
    private View _view;
    private ViewModel _viewModel;

    public ViewController()
    {
        ICommand closeView = new DelegateCommand(m => closeView());
        this._view = new View();
        this._viewModel = new ViewModel(closeView);
        this._view.DataContext = this._viewModel;
    }

    private void closeView()
    {
        this._view.close();
    }
}

public class ViewModel
{
    private bool _viewModelClosing;

    public ICommand CloseView { get;set;}

    public bool ViewModelClosing
    { 
        get { return this._viewModelClosing; }
        set
        {
            if (value != this._viewModelClosing)
            {
                this._viewModelClosing = value;
                // odd to do it this way.
                // better bind a button event in view 
                // to the ViewModel.CloseView Command

                this.closeCommand.execute();
            }
        }
    }

    public ViewModel(ICommand closeCommand)
    {
        this.CloseView = closeCommand;
    }
}
bhavik shah
  • 573
  • 5
  • 12