本当に 2 つの異なるアイテムをリンクする必要がありますか?それとも、リスト内の各オブジェクトに対して 2 つのアイテムの視覚的な外観 (上下) が必要なだけですか? 後者の場合は、ビュー モデルを定義し、XAML でアイテム テンプレートを指定できます。次に、コレクションが変更されたロジックの場合、 INotifyCollectionChanged を実装して CollectionChanged イベントを発生させる ObservableCollection を使用できます。
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>