Search code examples
c#wpfmvp

Why can't I call a method in my View's code-behind from the view's presenter?


This is the code-behind of my view:

using System.Windows.Controls;

namespace TestBoundTabControl.Views
{
    public partial class SmartFormView : UserControl
    {
        public SmartFormView()
        {
            InitializeComponent();
        }

        public void BeforeLoad()
        {
            MainTabControl.SelectedIndex = MainTabControl.Items.Count - 1;
        }
    }
}

But why can't I access the method "BeforeLoad()" from the view's presenter?

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using TestBoundTabControl.Views;

namespace TestBoundTabControl.Presenters
{
    public class SmartFormPresenter : PresenterBase
    {
        #region ViewModelProperty: SmartFormAreaPresenters
        private ObservableCollection<SmartFormAreaPresenter> _smartFormAreaPresenters = new ObservableCollection<SmartFormAreaPresenter>();
        public ObservableCollection<SmartFormAreaPresenter> SmartFormAreaPresenters
        {
            get
            {
                return _smartFormAreaPresenters;
            }

            set
            {
                _smartFormAreaPresenters = value;
                OnPropertyChanged("SmartFormAreaPresenters");
            }
        }
        #endregion

          public SmartFormPresenter()
        {
            View = new SmartFormView();
            View.DataContext = this;


            for (int i = 0; i < 5; i++)
            {
                SmartFormAreaPresenters.Add(new SmartFormAreaPresenter());
            }

            View.BeforeLoad(); //method not found

        }
    }
}

Solution

  • My guess is that the property View has type UserControl and not SmartFormView. If that is true you will have to cast it (or change it's type):

    ((SmartFormView) View).BeforeLoad();