C#使用对象绑定ListView项

时间:2011-05-31 13:52:46

标签: c# winforms listview

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

4 个答案:

答案 0 :(得分:5)

您可以使用可观察的集合,并为Card类创建数据模板。然后,您只需将ListView绑定到集合,它就会为您完成所有工作。当您将项目添加到ObservableCollection ListView时会自动重绘。

using System.Collections.ObjectModel;

<ListView Name="allCardsView" Source="{Binding}">
    <ListView.ItemTemplate>
        <DataTemplate DataType="{x:Type yourXmlns:Card}">
            //Your template here
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>
<ListView Name="selectedCardsView" Source="{Binding}">
    <ListView.ItemTemplate>
        <DataTemplate DataType="{x:Type yourXmlns:Card}">
            //Your template here
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

ObservableCollection<Card> allCards = new ObservableCollection<Card>();
ObservableCollection<Card> selectedCards = new ObservableCollection<Card>();
allCardsView.DataContext = allCards;
selectedCardsView.DataContext = selectedCards;


public void ButtonClickHandler(object sender, EventArgs e) 
{
    if (allCardsView.SelectedItem != null &&
        !selectedCards.Contains(allCardsView.SelectedItem)) 
    {
        selectedCards.Add(allCardsView.SelectedItem);
    }
}

答案 1 :(得分:5)

要扩展@ CharithJ的答案,这就是你如何使用tag属性:

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

显然,你需要根据自己的代码进行调整,但这应该让你开始。

答案 2 :(得分:1)

第一道。

将对象分配给ListViewItem的Tag属性。获取所选项目的标签。

第二种方式。

将不可见的subItem添加到包含Card对象ID的listView。然后使用所选的项目ID找到该卡片。

答案 3 :(得分:1)

更好地使用ObjectListView。这是使用ListView添加和使用对象的完美方式。通过热跟踪和易于使用的拖放功能,您的列表视图变得更容易操作。