I have two classess and a Userform. I am trying not to use any Form related code in my classess but i am rather new to OOP. In the CreateGraph() method, i would like to prompt the user with a Yes/No dialog. The code in the method would continue based on the result. I have read some examples on MVP but not exactly sure how i can implement in this case.
Can someone guide me on this? I do believe there is some serious design issues in my code
//singleton class
public class MyApplication
{
private int state;
private static MyApplication instance = null;
public void Task1()
{
GraphGenerator gg = new GraphGenerator();
gg.CreateGraph();
state = 1;
}
public void Task2()
{
//some other tasks..
state = 2;
}
}
Class where i have issue..
public class GraphGenerator
{
public void CreateGraph()
{
//some code for creating a graph..
//here i want to prompt the user with a
// Yes/No dialog box..
}
}
The userform
public partial class Form1 : Form
{
private void btnTask1_Click(object sender, EventArgs e)
{
MyApplication ma = MyApplication.Instance;
ma.Task1();
}
private void btnTask1_Click(object sender, EventArgs e)
{
MyApplication ma = MyApplication.Instance;
ma.Task2();
}
}
First , it is best to design your classes as much as possible such that you don’t need to intermingle UI code with your domain objects. Can you restructure the code so that the caller/owner of
GraphGeneratordecides if it needs to ask the user something instead ofGraphGeneratordoing it? Try to keepGraphGeneratorsolely focused on his task or making graphs.Failing that, you could define events (or delegates or callback interface, but lets call these related mechanisms events for now) within
GraphGeneratorsuch that the caller/owner can listen for notifications fromGraphGeneratorand in turn interact with the user. For example, define an event calledQueryConfirmSaveto raise and the caller can handle the event and prompt the user and then pass back a boolean as an EventArg field.(The code would be something like this (from the hip, not editor checked):
and then: