[英]Linking items in a Listbox C#
有沒有一種方法可以將ListBox
兩個項目鏈接在一起? 我要完成的工作是允許用戶刪除ListBox
的項目,並且在刪除該項目之前,如果它是偶數,則刪除它上面的一個項目;如果是奇數,則刪除一個項目。 還是我應該使用其他東西代替ListBox
? 這是我的代碼中處理刪除內容的部分:
private void DeleteItem(string path)
{
var index = FileList.IndexOf(path);
if (index % 2 == 0)
{
FilesList.RemoveAt(index + 1);
}
else
{
FileList.RemoveAt(index - 1);
}
FileList.Remove(path);
}
您是否真的需要鏈接兩個不同的項目,或者僅僅是對於列表中的每個對象都需要兩個項目的外觀(一個在另一個之上)? 如果是后者,則可以定義視圖模型並在XAML中指定項目模板。 然后,對於集合更改邏輯,可以使用ObservableCollection,它實現INotifyCollectionChanged並引發CollectionChanged事件。
public partial class MainWindow : Window
{
class ListItemViewModel
{
public string Name1 { get; set; }
public string Name2 { get; set; }
}
ObservableCollection<ListItemViewModel> items;
public MainWindow()
{
InitializeComponent();
// Populate list...
// In reality, populate each instance based on your related item(s) from your data model.
items = new ObservableCollection<ListItemViewModel>
{
new ListItemViewModel { Name1 = "Foo1", Name2 = "Foo2" },
new ListItemViewModel { Name1 = "Bar1", Name2 = "Bar2" }
};
listBox1.ItemsSource = items;
items.CollectionChanged += items_CollectionChanged;
}
void items_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
switch (e.Action)
{
case NotifyCollectionChangedAction.Remove:
for (int i = 0; i < e.OldItems.Count; i++)
{
var itemVm = e.OldItems[i] as ListItemViewModel;
// Update underlying model collection(s).
}
break;
// Handle cases Add and/or Replace...
}
}
}
XAML:
<ListBox x:Name="listBox1">
<ListBox.ItemTemplate>
<ItemContainerTemplate>
<StackPanel>
<TextBlock Text="{Binding Name1}" />
<TextBlock Text="{Binding Name2}" />
</StackPanel>
</ItemContainerTemplate>
</ListBox.ItemTemplate>
</ListBox>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.