C# 将 ListView 项目与对象绑定(bind)

标签 c# winforms listview

什么是将 ListView 项目与对象绑定(bind)的最佳方法,因此当我将项目从一个 ListView 移动到另一个 ListView 时,我仍然能够告诉它分配给哪个对象。 例如,我有对象 Cards。所有这些都列在 allCards ListView 中。我有另一个 selectedCards ListView 和一个按钮,用于将所选项目从一个 ListView 移动到另一个 ListView 。当我完成选择后,我需要获取移动到 selectedCards ListView 的 Card 对象的列表。

最佳答案

为了扩展@CharithJ 的回答,这是您使用标记属性的方式:

    ListView allCardsListView = new ListView();
    ListView selectedCardsListView = new ListView();
    List<Card> allCards = new List<Card>();
    List<Card> selectedCards = new List<Card>();
    public Form1()
    {
        InitializeComponent();


        foreach (Card selectedCard in selectedCards)
        {
            ListViewItem item = new ListViewItem(selectedCard.Name);
            item.Tag = selectedCard;
            selectedCardsListView.Items.Add(item);
        }
        foreach (Card card in allCards)
        {
            ListViewItem item = new ListViewItem(card.Name);
            item.Tag = card;
            allCardsListView.Items.Add(new ListViewItem(card.Name));
        }

        Button button = new Button();
        button.Click += new EventHandler(MoveSelectedClick);
    }

    void MoveSelectedClick(object sender, EventArgs e)
    {
        foreach (ListViewItem item in allCardsListView.SelectedItems)
        {
            Card card = (Card) item.Tag;
            //Do whatever with the card
        }
    }

显然,您需要根据自己的代码对其进行调整,但这应该让您入门。

关于C# 将 ListView 项目与对象绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6188636/

相关文章:

c# - 从任务体内取消任务

java - 在绑定(bind) ListView 之前从数据库中分割字符串

android - 从类获取值时出现空指针异常

c# - 设置STS但在webapp中保留formauthentication

c# - 调试 beta C# 桌面应用程序的最佳方法是什么

c# - 在 Excel 图表 c# 中旋转 X 轴

c# - Listview Details View 不显示任何内容

c# - 如何避免在多个文件中有条件地使用相同的命名空间

c# - Datagridview FirstDisplayedScrollingRowIndex 在网格底部不起作用

android - ListView 在数据更改后强制重新膨胀列表行布局