user2714823 user2714823 - 4 years ago 111
C# Question

Selecting Keys as SelectedItems in ListView

I have a dictionary bind to ListView and have two columns .It supports multiple selection an an Ok button . Now after selecting items from listview i only want the 1st column i.e the keys of dictionary to be saved in a list list1.
Help needed :)

Here is the back end code :-

public partial class MainWindow : Window
public List<string> list1

public MainWindow()
Dictionary<int, string> list = new Dictionary<int, string>();
list.Add(1, "a");
list.Add(2, "b");

lvUsers.ItemsSource = list;
lvUsers.SelectedIndex = 0;

public void getSelectedItem(Object sender, RoutedEventArgs e)
// Here is the part where you get the keys of selected items



The Xaml code :-


<RowDefinition Height="*"/>
<RowDefinition Height="*"/>

<ListView Margin="10,10,10,0" Name="lvUsers" SelectionMode="Multiple" Grid.Row="0">
<GridViewColumn Header="column1" Width="120" DisplayMemberBinding="{Binding Key}" />
<GridViewColumn Header="column2" Width="50" DisplayMemberBinding="{Binding Value}" />

<Button x:Name="getitem" Click="getSelectedItem" Grid.Row="1" Content="ok" />

Answer Source

Something like this should do the trick:

var keys =  lvUsers.SelectedItems.OfType<KeyValuePair<int, string>>().Select(x => x.Key);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download