WPF: get my object after ListView context menu right click instead of item index

334 views Asked by At

I have ListView contains my object:

public ObservableCollection<MyObject> objects { get; set; }

This is my Context menu right click event:

private void MenuItem_Click(object sender, RoutedEventArgs e)
{
    if (myListView.SelectedIndex == -1)
        return;
    int index = myListView.SelectedIndex;
}

So instead of take this index and find my object in my collection base on index number can i take the object at once ?

1

There are 1 answers

0
olitee On BEST ANSWER

If I understand you correctly, you want to just fetch the object that has been selected

Have you tried using the .SelectedItem property of the list view?

private void MenuItem_Click(object sender, RoutedEventArgs e)
{
    if (myListView.SelectedIndex == -1)
        return;
    var obj = myListView.SelectedItem as MyObject;
}

Although I'm not sure why you can't just look up the object by its index in the collection. Both approaches would be valid, although the above approach has clearer intentions.