本文介绍了如何从自另一类的listBox1_SelectedIndexChanged事件的价值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表框,我也有一个 listBox1_SelectedIndexChanged 事件多code主窗体持续了每一个项目时,它改变。

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?

如果不是,我的意思,我不希望这一切code在我的主窗体的code,所以我想将它移动到另一个类的地方有较大关系。

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.

什么是最佳实践的方式来通知 B类 listBox1_SelectedIndexChanged 发生?它是通过一个委托?我试图弄明白,但并没有真正理解。帮助将非常AP preciated。

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.

感谢。

推荐答案

我不知道如何这两个类都与对方和自己的类型,但使用以下code,你可以得到的想法来解决你的问题。

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;
   }
}

这篇关于如何从自另一类的listBox1_SelectedIndexChanged事件的价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 09:09