c# - 使用 SelectionMode Multiple/Extended 跨多个嵌套列表框获取所有选定项

标签 c# wpf xaml listbox nested

我有一个 ListList 并用嵌套的 ListBoxes 显示它:

MainWindow.xaml.cs

using System.Collections.Generic;

namespace WPF_Sandbox
{
    public partial class MainWindow
    {

        public IEnumerable<IEnumerable<string>> ListOfStringLists { get; set; } = new[] { new[] { "a", "b" }, new[] { "c", "d" } };

        public MainWindow()
        {
            InitializeComponent();

            DoSomethingButton.Click += (sender, e) =>
            {
                // do something with all selected items
            };
        }

    }
}

MainWindow.xaml

<Window x:Class="WPF_Sandbox.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow"
        x:Name="ThisControl">
    <StackPanel>
        <ListBox ItemsSource="{Binding ListOfStringLists, ElementName=ThisControl}">
            <ListBox.ItemTemplate>
                <ItemContainerTemplate>
                    <ListBox ItemsSource="{Binding}" SelectionMode="Multiple">
                        <ListBox.ItemTemplate>
                            <ItemContainerTemplate>
                                <TextBlock Text="{Binding}" />
                            </ItemContainerTemplate>
                        </ListBox.ItemTemplate>
                    </ListBox>
                </ItemContainerTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
        <Button Name="DoSomethingButton" Content="DoSomething" />
    </StackPanel>
</Window>

如何获取所有 ListBoxes 中的所有选定项?

我找到了一个 few solutions得到一个选定的项目,但无法弄清楚如何在我的场景中应用这些项目。
我有一个关于如何通过包装 string 数组来做到这一点的想法,但我不想这样做。

最佳答案

如果不以 MVVM 方式做事,我会像这样向内部 ListBox 添加一个事件处理程序:

<ListBox ItemsSource="{Binding}" SelectionMode="Multiple" SelectionChanged="ListBox_SelectionChanged">

然后在后面的代码中像这样实现 ListBox_SelectionChanged:

public List<string> FlatStringList = new List<string>();
private void ListBox_SelectionChanged(object sender,System.Windows.Controls.SelectionChangedEventArgs e)
{
    FlatStringList.AddRange(e.AddedItems.Cast<string>());
    foreach(string s in e.RemovedItems)
    {
        FlatStringList.Remove(s);
    }            
}

这是假设您不介意将选定的字符串存储在平面列表中。然后您可以实现您的 DoSomething 按钮单击事件处理程序以使用 FlatStringList 执行某些操作。 希望对您有所帮助。

关于c# - 使用 SelectionMode Multiple/Extended 跨多个嵌套列表框获取所有选定项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42348393/

相关文章:

c# - 在 Entity Framework 中使用投影的扩展方法

c# - 在单引号中设置参数值的Postgres准备语句错误

c# - 移至CollectionViewSource中的特定项目?

c# - XAML中设置属性的顺序是什么?

wpf - ListView 中 Gridview 列的内容对齐

C# Xml 反序列化,忽略 XML 中的数据

C# ‘dynamic’ 无法访问在另一个程序集中声明的匿名类型的属性

c# - WPF - 仅当超链接被禁用时如何在超链接上显示工具提示

wpf - 具有自定义排序的 CollectionViewSource

wpf - WPF工具栏项目Horizo​​ntalAligment =“右”