【问题标题】:.net add item from listbox to another project in the same solution.net 将列表框中的项目添加到同一解决方案中的另一个项目
【发布时间】:2013-09-20 14:28:43
【问题描述】:

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

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

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

谢谢

【问题讨论】:

    标签: .net winforms listbox controls


    【解决方案1】:

    确实可以。

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

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

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

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

    例如

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-19
      • 1970-01-01
      • 1970-01-01
      • 2021-08-19
      相关资源
      最近更新 更多