简体   繁体   中英

How can I access the MainForm from within a class in a separate project?

I have two projects in this solution: ProjectA and ProjectB. ProjectA is the main start-up project, and has a reference to ProjectB.

ProjectA has a file called MainForm.cs, which contains a textbox and the main UI.

ProjectB has a class inside Shapes.cs, containing a particular structure we're using. Shapes.cs contains an event that is fired when the user changes some text for that object.

What I need to do is catch that text and set a textbox in MainForm.cs to that text. Is there a way we can do that? Basically I don't see any reference to the main form inside Shapes.cs. I would like to do something like this:

( Shape1.Parent as MainForm ).TextBox1.Text = Shape1.Name;

, assuming the user types a string that gets stored in Shape1.Name. I need to escalate it to the main form.

I have searched around for other questions, and the closest lead I found was Matt Hamsmith's answer on this question. But if it is a good approach I should follow, I do not know how to assign an event handler in the main form to an event in the separate class. I would appreciate any help.

Thanks.

If the form is made up child controls, it should be listening to events on those controls, rather than the controls trying to cast their parent as a particular type. Doing that means your control will only ever work on that Form. It breaks encapsulation.

Listen to an event like this:

public class MainForm : Form
{
    Shape _shape1 = new Shape();

    public MainForm()
    {
        InitializeComponent();
        _shape.ShapeNameChanged += HandleShapeNameChanged;
    }

    public void HandleShapeNameChanged(object sender, ShapeChangeEventArgs e)
    {
        textBox1.Text = e.NewName;
    }
}

public class Shape
{
    public event EventHandler<ShapNameChangedEventArgs> ShapeNameChanged;
}

I've left it for you to:

  1. Define the ShapeNameChangedEventArgs object to contain whatever state you want it to.
  2. Invoke the event when something on your control changes.

Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM