Search code examples
c#wpflistviewdata-binding

WPF - Get bound source object from ListView.SelectedItem


I have a ListView item that is bound to a List<MyObject> collection. MyObject has various methods that I'd like to invoke, e.g. when a user selects an item from the ListView and then clicks on a button to perform an action on that individual SelectedItem.

XAML:

<ListView x:Name="lvMyListView">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Title" DisplayMemberBinding="{Binding myProperty}"/>
        </GridView>
    </ListView.View>
</ListView>

Code:

// WPF window constructor
public MyWindow()
{
    InitializeComponent();
    List<MyObject> myItems = new List<MyObject>();
    this.SourceInitialized += MyWindow_SourceInitialized;
    lvMyListView.ItemsSource = myItems;
}

// MyObject definition
class MyObject : INotifyPropertyChanged
{
    ...
    public string myProperty { get; set; }
    public void DoSomething()
    {
        ...
    }
}

// Button event
private void myButton_Click(object sender, RoutedEventArgs e)
{
    // MyObject currentItem = lvMyListView.SelectedItem;
    // currentItem.DoSomething();
}

How can I get the actual instance of MyObject that is being represented by ListView.SelectedItem? Thanks for any help.


Solution

  • I have read your question several times. It seems to me that you are mixing the MVVM and normal backend coding together and that is making your code hard to read and understand.

    There are, I believe 2 ways you can access the object. If I get what you asked correctly. You can either cast :

    MyObject currentItem = lvMyListView.SelectedItem as MyObject; 
    

    or use lvMyListView.SelectedIndex against your original list.

    Also note that first option can be null if not selected and second one can be -1 so add checks accordingly.

    But, a better approach is to use MVVM and data binding altogether. It's longer than I can write here but you create a view model object and bind the selected item property of the list to one of it's properties also your button would trigger an action in the view model class. This is a better approach to WPF coding. So please check that out.