2011-05-31 133 views
6

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

+0

这个问题不是很清楚。如果你将这些对象移动到'selectedCards',是不是你想要的列表? – 2011-05-31 14:02:28

+0

@Steven:在ListView中只有卡片的名称.. – hs2d 2011-05-31 14:05:54

+0

只是一个小建议,如果你将所有卡片重新命名为availableCards *,它会更干净... ... – 2011-05-31 14:08:15

回答

5

为了扩大对@ 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 
     } 
    } 

很显然,你需要以使其适应自己的代码,但是这应该让你开始。

+0

我知道这个答案是旧的,但这完全是***我正在寻找的东西。我从来不知道“Tag”属性,也不知道它做了什么或者做了什么,所以非常感谢:D – Nolonar 2013-03-25 13:34:52

1

第一种方式。

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

第二种方式。

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

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); 
    } 
} 
+0

对不起,我忘记说使用WinForms即时通讯。 – hs2d 2011-05-31 16:37:05

1

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

相关问题