3yakuya
3yakuya

Reputation: 2672

Finding index of clicked element in WPF GridView

I have a GridView of elements, I want to perform some operations when one of the elements is clicked. So I set ItemClick property of the GridView to TopicsPage_ItemClick and implement the method. I tried to react like this (a few of attempts):

private void TopicsPage_ItemClick(object sender, ItemClickEventArgs e)
{
    int index = itemGridView.SelectedIndex;
    string topicName = this.topicList[index].Name;
    this.Frame.Navigate(typeof(CardsPage), topicName);
}

private void TopicsPage_ItemClick(object sender, ItemClickEventArgs e)
{
    int index = itemGridView.Items.IndexOf((e.ClickedItem as FrameworkElement));
    string topicName = this.topicList[index].Name;
    this.Frame.Navigate(typeof(CardsPage), topicName);
}

private void TopicsPage_ItemClick(object sender, ItemClickEventArgs e)
{
    var item = (sender as FrameworkElement).DataContext;
    int index = itemGridView.Items.IndexOf(item);
    string topicName = this.topicList[index].Name;
    this.Frame.Navigate(typeof(CardsPage), topicName);
}

But every solution above throws ArgumentOutOfRangeException with index = -1. I have exactly the same solution on another page, where I have buttons in GridView and implement Click of them, and it works there. Any advice would be apprecitated.

Upvotes: 2

Views: 1052

Answers (1)

Chubosaurus Software
Chubosaurus Software

Reputation: 8161

Gonna assume your GridView ItemsSource is bind to a collection.

Here are the behaviors from my experience if you have IsItemClickEnabled="True" the ItemClick event will fire BUT the SelectionChanged will not fire leaving you with the SelectedIndex of -1.

To get the index you can you grab it by casting it from the IndexOf

private void TopicsPage_ItemClick(object sender, ItemClickEventArgs e)
{
    GridView gv = sender as GridView;
    index = gv.Items.IndexOf(e.ClickedItem);   // don't re cast it as anything; just past it
}

You can also get it from the GridView.ItemsSource collection.IndexOf as well if you like

Upvotes: 3

Related Questions