【问题标题】:wpf listbox to get selected value(s) using LINQ使用 LINQ 获取选定值的 wpf 列表框
【发布时间】:2013-05-24 13:47:01
【问题描述】:

我是 LINQ 的新手。我想在使用 WPF 的项目中使用它。每个 wpf 页面都有两个列表框(第一个 wpf 页面中的 ListBox1 和第二个 wpf 页面中的 ListBox2)。我需要将选定的值从 ListBox1 传递到 ListBox2。

第一个 WPF 页面:ListBox1

private void btnNext_Click(object sender, RoutedEventArgs e)
    {
            List<FoodInformation> _dinners = (from ListItem item in ListOfFood.Items
                                             where item.selecteditem select item).ToList(); 

            //(above: this linq - item.SelectedItems doesnt work. How?)

            var passValue = new ScheduleOperation(_dinners);

            Switcher.Switch(passValue); //go to another page 
    }

第二个 WPF 页面:ListBox2

public ScheduleOperation(List<FoodInformation> items)
        : this()
    {
        valueFromSelectionOperation = items;
        ListOfSelectedDinners.ItemsSource ;
        ListOfSelectedDinners.DisplayMemberPath = "Dinner";
    }

非常感谢您对编码的帮助。谢谢!

【问题讨论】:

  • 你知道 ListBox 有 SelectedItems 属性,对吧(不需要 LINQ)?

标签: linq listbox


【解决方案1】:

除了我对您的问题的评论之外,您还可以执行以下操作:

        var selectedFromProperty = ListBox1.SelectedItems;
        var selectedByLinq =  ListBox1.Items.Cast<ListBoxItem>().Where(x=>x.IsSelected);

只要确保列表框中的每个项目都是 ListBoxItem 类型。

【讨论】:

    【解决方案2】:

    为了后代……

    一般来说,要在 LINQ 中使用某些东西,您需要一个 IEnumerable。 Items 是 ItemCollection,SelectedItems 是 SelectedItemCollection。他们实现了 IEnumerable,但没有实现 IEnumerable。这允许将各种不同的东西放入一个 ListBox。

    如果您没有明确地将 ListBoxItems 放入列表中,则需要强制转换为您实际放入列表中的项目的类型。

    例如,使用 XAML 的字符串:

    <ListBox Height="200" SelectionMode="Multiple" x:Name="ListBox1">
        <system:String>1</system:String>
        <system:String>2</system:String>
        <system:String>3</system:String>
        <system:String>4</system:String>
    </ListBox>
    

    或使用 C#:randomListBox.ItemsSource = new List&lt;string&gt; {"1", "2", "3", "4"};

    ListBox1.SelectedItems 需要转换为字符串:

    var selectedFromProperty = ListBox1.SelectedItems.Cast<string>();
    

    虽然可以从 Items 中获取选定的项目,但这确实不值得,因为您必须找到 ListBoxItem(此处解释:Get the ListBoxItem in a ListBox)。你仍然可以这样做,但我建议这样做。

    var selectedByLinq = ListBox1.Items
        .Cast<string>()
        .Select(s => Tuple.Create(s, ListBox1.ItemContainerGenerator
             .ContainerFromItem(s) as ListBoxItem))
        .Where(t => t.Item2.IsSelected)
        .Select(t => t.Item1);
    

    请注意,ListBox 默认为虚拟化,因此 ContainerFromItem 可能返回 null。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-21
      • 2013-10-27
      • 1970-01-01
      • 1970-01-01
      • 2016-01-18
      • 1970-01-01
      • 2010-11-20
      • 1970-01-01
      相关资源
      最近更新 更多