Pass value from parent form to child form?

后端 未结 3 671
梦如初夏
梦如初夏 2021-01-27 18:36

I\'m trying to pass a value set in my parent form to a second form. I created a property with a get part in the parent form.

I don\'t want to do something like:

3条回答
  •  天命终不由人
    2021-01-27 19:00

    You have some possibilities here:

    Give a Reference from your first Form as value

    Form2 secondForm = new Form2(yourForm1);
    

    So you can access via the getter in your first Form. yourForm1.MyValue;

    This seems to be a bit ugly. Better is you create a Interface, which hold your Property and is implemented from you first Form.

    public interface IValueHolder
    {
       public int MyValue {get;}
    }
    
    public class FirstForm : Form, IValueHolder
    {
       public int MyValue{get;}
    
       //Do your form stuff
    
       Form2 form = new Form2(this);
    }
    

    So your Form2 just take the Interface and stays independent from Form1. Further you can create a Property on Form2 which you access from Form1. For example if your Property in Form1 changes you set the value from Form2 as well.

    public class Form2 : Form
    {
       public int MyValue{get;set;}
    }
    
    public class Form1 : Form
    {
      private int _myValue;
      public int MyValue
      {
         set
         {
            if (_myValue != value)
            {
               form2.MyValue = value;
            }
         }
      }
    }
    

    At least you can use a Event maybe. Further you can create a Property on Form2 which holds an Form1 Reference or a IValueHolder as described above.

    Hope this helps.

提交回复
热议问题