.net将列表框中的项添加到同一解决方案中的另一个项目

时间:2013-09-20 14:28:43

标签: .net winforms listbox controls

我正在开发一个包含多个项目的.NET 4项目。 主要项目是列表框中的Windows应用程序。 在相同的解决方案中,我有一个类库项目。

在我的Windows窗体后面的代码中,我在类库中调用了一个函数。

我可以将我的项目列表框控件传递到同一解决方案中的另一个项目并添加到项目中吗?

谢谢

1 个答案:

答案 0 :(得分:0)

确实可以。

但首先在类库中添加对System.Windows.Controls的引用。 然后,您可以在其中一个类上使用公共方法

public void DoSomethingToMyListBox(ListBox list)
{
   list.Clear(); //or whatever
}

然而。我会请你考虑一下你想用这个列表框做什么,以及为什么你需要把它传递给另一个模块 - 一般来说这是你设计中的一个缺陷的标志。

例如,如果你想传递它,因为你想用一些来自数据库的项目填充它,并且你想要将主要的Forms项目与数据库访问隔离(一件好事)那么你应该有您的类库返回data,您应该使用Windows窗体数据绑定组件。

e.g

//on your Form's code
public Form1()
{
   var myThing =new MyClass(); //whatever the class in the class library is called
   var theData = MyClass.GetData(); //GetData returns List<something>
   MyListBox.DataSource=theData;
//if "something" is a class, use the two lines below
 //if something is just a list of strings for example, you don't need to bother
   MyListBox.DisplayMember="name of property on something to display in the list";
   MyListBox.ValueMember="name of property on something to use as list index";

}

当然我不知道这是不是你想做的事情:)