0

ListBox2 つのアイテムを一緒にリンクする方法はありますか? 私が達成しようとしているのは、ユーザーがアイテムを削除できるようにすることです。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);        
}
4

1 に答える 1

1

本当に 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>
于 2013-02-03T17:44:04.747 に答える