5

My question is regarding implementing MVC pattern in winforms

I learned that the controller object is responsible for handling the events raised in the view. Can any one please tell me how can the controller reacts to the text input or button press event in the view? I mean how can the controller know that some event happened without it being handled in the view as these controls(textbox,button) are private to view.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
logeeks
  • 4,849
  • 15
  • 62
  • 93

3 Answers3

7

The idea is that the view catches the event and then call on an appropriate function in the controller. In Windows Forms that means that you'll attach an event handler for e.g. "button_click", which then call on controller.doFoo().

You might be interessted in reading GUI Architectures at Martin Fowlers site.

  • I was obsessed(after reading articles) with the idea of the view playing dumb and the intelligent controller passing the information about the view-events it trapped to the view.I thought if I add the button_click event handler behind the view code-behind,MVC purists will throw stones at me. – logeeks Nov 14 '11 at 15:04
6
 public partial class Form1 : Form
    {
        private Controller controller;
        public Form1()
        {
            InitializeComponent();
        }
        //Dependency Injection
        public Form1(Controller controller):this()
        {
            //add more defensive logic to check whether you have valid controller instance
            this.controller = controller;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            if (controller != null)
                controller.MethodA();
        }
    }
    //This will be another class/ controller for your view.
    public class Controller
    {
        public void MethodA() { }
    }
s_nair
  • 812
  • 4
  • 12
3

In case of WinForms, I think you should consider using the MVP pattern.

andrew
  • 1,030
  • 2
  • 8
  • 21