2

我是 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";
    }

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

4

2 回答 2

1

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

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

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

于 2013-05-24T15:47:05.350 回答
1

为了后代...

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

如果您没有明确地将 ListBoxItems 放入列表中,则需要 Cast 以键入您实际放入列表中的项目。

例如,使用 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<string> {"1", "2", "3", "4"};

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

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

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

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。

于 2016-08-23T21:26:48.540 回答