Possible Duplicate:
WPF Listview Access to SelectedItem and subitems
I have a listview defined as such:
<ListView Height="234.522" Name="chartListView" Width="260" SelectionChanged="chartListView_SelectionChanged" HorizontalAlignment="Left" Margin="251,38,0,38">
<ListView.View>
<GridView>
<GridViewColumn Header="op1" DisplayMemberBinding="{Binding op1}" Width="50"/>
<GridViewColumn Header="op2" DisplayMemberBinding="{Binding op2}" Width="50"/>
<GridViewColumn Header="op3" DisplayMemberBinding="{Binding op3}" Width="50"/>
<GridViewColumn Header="op4" DisplayMemberBinding="{Binding op4}" Width="50"/>
<GridViewColumn Header="op5." DisplayMemberBinding="{Binding op5}" Width="50"/>
</GridView>
</ListView.View>
</ListView>
I add data using the following:
chartListView.Items.Add(new {
op1 = "test1", op2 = "test2", op3 = "test3", op4 = "test4", op5 = "test5" });
How do I access one of the selected items so that I can see which value a column has (op3 for example)? The following code shows ALL of the values but I would only like to see op3.
MessageBox.Show(chartListView.SelectedItem.ToString());
I would suggest to use the MVVM pattern in order to connect your UI with an underlaying logic.
On the Internet you will find plenty of information and resources regarding the M*VVM pattern*.
The core idea is to have a ViewModel (VM) which holds data structures and variables. These data structures and variables are completely autonomous and are not depending on the UI layer in any way. The connection of the structures and variable from your VM to your UI/View (V) lies in DataBindings.
So what you have to do (in very short terms) is to connect the ItemSource property of your list control with some underlaying data structure (the usual structure here is an ObservableCollection – read the literature to find out why).
That’s the first step. A second step might be to add a variable of type object to your ViewModel that will hold the currently selected item of your list. To make this work you only have to connect the SelectedItem – property of your list with this variable.
From then on whenever you select an item in your list your variable in the View is holdings its value.
Of course this is very short termed and rather sketchy but maybe it gave you the idea to dig deeper into the MVVM pattern – it’s pretty well-thought 😉