hs2*_*s2d 6 c# listview winforms
什么是将ListView项目与对象绑定的最佳方式,因此当我将项目从一个列表视图移动到另一个列表视图时,我仍然能够告诉它分配了什么对象.例如,我有对象Cards
.所有这些都列在一个allCards
ListView
.我有另一个selectedCards
ListView
按钮,将所选项目从一个列表视图移动到另一个列表视图.当我完成我的选择时,我需要获取Card
移动到selectedCards
ListView 的对象列表.
您可以使用可观察的集合,并为您的Card
类创建一个datatemplate .然后你只需要绑定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);
}
}
Run Code Online (Sandbox Code Playgroud)
要扩展@ 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
}
}
Run Code Online (Sandbox Code Playgroud)
显然你需要根据自己的代码进行调整,但这应该让你开始.