【问题标题】:Linking items in a Listbox C#链接列表框中的项目 C#
【发布时间】:2013-02-03 16:58:19
【问题描述】:

有没有办法将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);        
}

【问题讨论】:

  • 您可能应该添加几个测试。找到路径了吗?这是第一项还是最后一项?
  • 为什么不使用树视图。我不认为你描述的最好使用列表框来完成:)?
  • 也许我应该更详细地了解正在发生的事情。首先,用户选择要比较的目录以查看是否有相同的文件。如果有匹配项(目前基于文件名),它将这两个项目添加到列表框中。所以应该找到路径(除非用户走出程序并删除它)。我考虑过使用树视图,但对列表框更熟悉,所以走那条路

标签: c# wpf listbox filelist


【解决方案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>

【讨论】:

  • 这似乎是我正在寻找的。我会尝试一下,甚至没有想到创建一个包含两个路径的类并制作一个集合。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-14
  • 1970-01-01
  • 2017-08-15
  • 1970-01-01
  • 2023-04-08
  • 2022-01-04
  • 1970-01-01
相关资源
最近更新 更多