How to get the value from a listBox1_SelectedIndex

2019-08-06 19:31发布

问题:

I have a main form with a listbox, I also have a listBox1_SelectedIndexChanged event and more code going on for each item when it changes.

Is there a simple way to make this event in another class and not on the main form?

If not, as I meant, I don't want all this code on my main form's code so I want to move it to another class where it is more related.

what is the "best practice" way to notify Class B when listBox1_SelectedIndexChanged occurs? is it by a delegate? I tried to figure it out but didn't really understand. Help will be much appreciated.

Thanks.

回答1:

I am not sure how both classes are linked to each other and their types but using following code you can get idea to solve your problem

public class A
{
   public delegate void ItemSelectedHandler(string title);
   public event ItemSelectedHandler OnItemSelected;
   public void listBox1_SelectedIndexChanged(object sender, EventArg, e)
   {
       //other code
       if(OnItemSelected!=null)
       {
          OnItemSelected("Something");
       }
   }
   public void LaunchB()
   {
      var b = new B(this);
      b.ShowDialog();
   }
}

public class B
{
   private A _parent;
   public B(A parent)
   {
      _parent = parent;
      _parent.OnItemSelected += onItemSelected;
   }
   public void onItemSelected(string title)
   { 
      //will fire when selected index changed;
   }
}


回答2:

I think I solved my question in a simpler way.

  1. I set the listbox1 access modifier to Internal
  2. I created properties for the main form.
  3. In Class B, I subscribed to the listBox1.SelectedIndexChanged event and created an event handler like this:

form1Properties.listBox1.SelectedIndexChanged+=listBox1_SelectedIndexChangedforClassB;

  1. Then I've implemented the event handler in Class B like this:

private void listBox1_SelectedIndexChangedforClassB(object sender, EventArgs e) { MessageBox.Show("listbox1 selected item has changed!"); }

I hope I am using all the right terms, please correct me if I'm wrong, and please tell me if you find my solution is flawed in any way. Thanks.



标签: c# .net oop