gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 23:03:07 25 4
gpt4 key购买 nike

我有一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com