Reputation: 447
I am new to LINQ. I would like to use it in my project using WPF. I have two listBoxes for each wpf page (ListBox1 in first wpf Page and ListBox2 in second wpf Page). I need to pass selected value(s) from ListBox1 to ListBox2.
The First WPF Page : 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
}
The Second WPF Page: ListBox2
public ScheduleOperation(List<FoodInformation> items)
: this()
{
valueFromSelectionOperation = items;
ListOfSelectedDinners.ItemsSource ;
ListOfSelectedDinners.DisplayMemberPath = "Dinner";
}
Your help with coding would be highly appreciated. Thanks!
Upvotes: 2
Views: 3064
Reputation: 765
For posterity sake...
In general, to use something with LINQ you need an IEnumerable<T>
. Items is an ItemCollection and SelectedItems is a SelectedItemCollection. They implement IEnumerable
, but not IEnumerable<T>
. This allows putting all kinds of different things into a single ListBox.
If you do not explicitly put ListBoxItems into your list, you need to Cast to type of the items you actually put in the list.
For instance, strings using 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>
or using C#: ListBox1.ItemsSource = new List<string> {"1", "2", "3", "4"};
ListBox1.SelectedItems needs to be casted to strings:
var selectedFromProperty = ListBox1.SelectedItems.Cast<string>();
Or alternatively, if you only care about the items that are of a given type, you can use OfType<T>
to just enumerate over the items are assignable to the type T
, like so:
var selectedFromProperty = ListBox1.SelectedItems.OfType<string>();
While it is possible to get the selected items from Items, it really isn't worth the effort, since you have to find the ListBoxItem (explained here: Get the ListBoxItem in a ListBox). You can still do it, but I do not it recommend it. Generally it is better to use MVVM with XAML.
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);
Be aware, that the ListBox defaults to virtualizing, so ContainerFromItem might return null.
Upvotes: 2
Reputation: 1449
In addition to my comment on your question, you can do something like this:
var selectedFromProperty = ListBox1.SelectedItems;
var selectedByLinq = ListBox1.Items.Cast<ListBoxItem>().Where(x=>x.IsSelected);
Just make sure every item in listbox is of ListBoxItem type.
Upvotes: 1