Reputation: 73
I'm having trouble implementing an interface on my main form. The idea is to have an interface, a controller class that sends the messages to the interface and my main form which implements the interface. This will be used by an object of another class to 'tell' the main form to update certain things. The problem I have is I cannot work out how to assign my main form to an instance variable of type interface in the controller class. I apologise if I'm not making this 100% clear. Examples of the classes below:
Main Form
using System;
using System.Windows.Forms;
namespace InterfaceProject
{
public partial class Form1 : Form, IMessage
{
public Form1()
{
InitializeComponent();
}
MessageController ctrl = new MessageController();
private void Form1_Load(object sender, EventArgs e)
{
ctrl.Greeting();
}
public void Hello()
{
//Do some stuff to the form
MessageBox.Show("Hello World");
}
}
}
Controller Class
namespace InterfaceProject
{
class MessageController
{
//Instance Variables
private IMessage messageClient;
//Constructor
public MessageController()
{
messageClient = Form1;
}
public void Greeting()
{
messageClient.Hello();
}
}
}
Interface
namespace InterfaceProject
{
interface IMessage
{
void Hello();
}
}
Upvotes: 2
Views: 1451
Reputation: 2123
The problem is that Form1 is not availiable in your MessageController class. You need to pass it as an argument to the MessageController constructor or create a setter function...
using System;
using System.Windows.Forms;
public partial class Form1 : Form, IMessage
{
private MessageController ctrl;
public Form1()
{
InitializeComponent();
ctrl = new MessageController(this);
}
private void Form1_Load(object sender, EventArgs e)
{
ctrl.Greeting();
}
public void Hello()
{
MessageBox.Show("Hello World");
}
}
class MessageController
{
private IMessage messageClient;
public MessageController(IMessageClient client)
{
messageClient = client;
}
public void Greeting()
{
messageClient.Hello();
}
}
interface IMessage
{
void Hello();
}
Upvotes: 3