Click here to Skip to main content
15,884,176 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi,

I'm new to WPF and C#. I've tried to seach the web for a simple tutorial or code on how I can capture the list of all the selected items in a listbox.

I am doing the following:

1. Have a List<ABC> where A has two properties: Name and Address.
2. I am using DataBinding to populate a ListBox by the following:

XAML:

<ListView Name="AddData" ItemsSource="{Binding}" DisplayMemberPath="Name" />

C#:

AddData.DataContext = XClass.getMyABCList(); // This returns the List<ABC>

This all works as I see the the Name property values in the ListBox.

Now, I want to select 3 of the items in the list. When I click on a "Done" button, I want to get the following information:

1) The indexes of the selected items
2) The Name values of the selected items
3) The Address values of the selected items.

I can obtain (2) and (3) if I can get (1) as I can cross reference the master List<abc>

Would appreciate any help in this.

Thanks,

Manish
Posted

1 solution

Rather than attempting to do this in a Win Forms manner, you can achieve this in a WPF-centric way by adding an IsSelected property to the class behind the list. Then you bind to this property using the following:
XML
<ListBox.ItemContainerStyle>
  <Style TargetType="{x:Type ListBoxItem}">
     <Setter Property="IsSelected" Value="{Binding Mode=TwoWay, Path=IsSelected}"/>
  </Style>
</ListBox.ItemContainerStyle>
Now your underlying list will have the IsSelected boolean set as appropriate, and you can just select the items where that value is set.
 
Share this answer
 
Comments
Manish V Mahajan 20-Jun-11 12:43pm    
Dude, Thanks a lot for this. I wouldn't have figured this out given that I am new to WPF and C#.

Can you kindly recommend any books or references on learning material....this would help greatly....Thanks again!!!
Pete O'Hanlon 21-Jun-11 3:57am    
Don't worry about it mate - we all had to start somewhere, and this stuff isn't obvious when you first start off. As for books, I'd recommend WPF Unleashed by Adam Nathan and Pro WPF in C# 2010 by Matthew MacDonald. Welcome to the world of WPF - it's one wild ride.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900