LololYut
LololYut

Reputation: 75

How to call a method of View in ViewModel?

I need to call a method of the View in the ViewNodel because in the View I can access different things that in the ViewModel not and I need to call that method. Is this possible to do?

Method in View:

  private void MyMethod(object sender, EventArgs e)
    {
        Book book = null;
        if (sender is StackLayout)
        {
            book = ((StackLayout)sender).BindingContext as Book;

            if (null == viewModel.BookSelected || !book.BookId.Equals(viewModel.BookSelected.BookId))
            {
                //Do something
            }
        }
    }

Upvotes: 2

Views: 1465

Answers (1)

Srijon Chakraborty
Srijon Chakraborty

Reputation: 2154

I think it is quite possible to access everything from view to viewmodel. If you are unable to do that in certain situation then, you can use event in your VM and raise that event when you need and you can bind a method that you want to call. Please check my sample code.

    public class View
    {
        ViewModel myVM = null;
        public View()
        {
            myVM=new ViewModel();
            myVM.CallMyMethodEvent += myViewMethod;
        }
        void myViewMethod(bool param)
        {
            //do you thing
        }
    }
    public class ViewModel
    {
        public Action<bool> CallMyMethodEvent;

        private void RaiseEventToCallMethodInView()
        {
            if (CallMyMethodEvent != null)
            {
                CallMyMethodEvent.Invoke(true);
            }
        }
    }

New Update Code as you want to call MyMethod() with 2 parameters. So, the code will look like =>

public class View
    {
        ViewModel myVM = null;
        public View()
        {
            myVM.CallMyMethodWithEventArgEvent += MyMethod;
        }
        private void MyMethod(object sender, EventArgs e)
        {
            if(sender is StackLayout)
            {
                var yourStackLayoutobject = (StackLayout)sender;
            }
        }
    }
    public class ViewModel
    {
        public Action<object, EventArgs> CallMyMethodWithEventArgEvent;
        private void RaiseEventToCallMethodWithEventArgInView()
        {
            if (CallMyMethodWithEventArgEvent != null)
            {
                CallMyMethodWithEventArgEvent.Invoke(new StackLayout(),null);
            }
        }
    }
    public class StackLayout
    {
    }

NOTE: Please check the code and let me know. I have used a dummy class StackLayout you can use your proper class.

Upvotes: 2

Related Questions