How to update list on one window when some event trigger on another window in WPF

后端 未结 3 1368
忘了有多久
忘了有多久 2021-01-25 15:40

How to update list on one window when some event trigger on another window in WPF. i just want to know how to listen to the event of one window from another window.

3条回答
  •  渐次进展
    2021-01-25 15:58

    What did you tried so far?

    Is one window creating the other window?

    Normally i would call a method of the child window. If the child window wants to trigger the parent, it should be done with an event.

    like: pseudo

    public class FormParent : Form
    {
    
        public void OpenChild()
        {
            // create the child form
            FormChild child = new FormChild();
    
            // register the event
            child.DataUpdated += Child_DataUpdated;
    
            // ....
    
            // parent to child (method call)
            child.DoSomething();
        }
    
        public void Child_DataUpdated(object sender, EventArgs e)
        {
             // refresh the list.
        }
    
    }
    
    public class FormChild : Form
    {
    
        public void DoSomething()
        {
    
            // ....
    
            // if the list should be refreshed.
    
            // call event from child to parent.
            if(DataUpdated != null)
                DataUpdated(this, EventArgs.Empty);
        }
    
    
        public event EventHandler DataUpdated;
    }
    

    Keep in mind, the parent knows the structure of the child. (method call) The child, doesn't know anything about the structure of the parent (events)

    This way you can reuse the child on different solutions. (not dependend on code)

提交回复
热议问题