0

有没有办法将两个项目链接ListBox在一起?我想要完成的是允许用户删除 a 中的项目,ListBox并且在删除该项目之前,如果它是偶数,它会删除它上面的一个项目,或者如果它是奇数,它会删除一个低于它的项目。还是我应该使用其他东西来代替 a 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

您真的需要链接两个不同的项目,还是只是需要列表中每个对象的两个项目的视觉外观(一个在另一个之上)?如果是后者,那么您可以定义视图模型并在 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 回答