Verint Verint
Verint Verint

Reputation: 567

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

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 ?

Upvotes: 1

Views: 334

Answers (1)

olitee
olitee

Reputation: 1683

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.

Upvotes: 1

Related Questions