best practices to call methods in the parent form and access gui elements in parent form in c#

后端 未结 3 506
刺人心
刺人心 2021-01-12 05:18

I am developing a win form app and I found myself constantly requiring to access methods in my parent form say Form1 from another class be it a form class or just a class. I

3条回答
  •  旧巷少年郎
    2021-01-12 05:52

    The way that I normally do this is to have the child form expose events corresponding to the logical actions and events on that form, for example:

    /// 
    /// Occurrs when an item is selected in the form
    /// 
    public event EventHandler ItemSelected;
    
    /// 
    /// Fires the  event
    /// 
    protected void OnItemSelected(MyItem item) 
    {
        var handler = this.ItemSelected;
        if (handler != null)
        {
            ItemSelectedEventArgs args = new ItemSelectedEventArgs();
            args.Item = item; // For example
            handler(this, args);
        }
    }
    

    The idea is that the logic of your parent form should respond to actions on your child form, rather than actions on your child form driving actions on the parent form - you should try to encapsulate the forms logic as much as possible (aka separation of concerns).

    Also as a pattern it should be the parent / calling form that handles marshalling the calls across to the correct thread via InvokeRequired etc... rather than the child form - this will be unneccessary anyway unless you are doing work on background threads.

提交回复
热议问题