简体   繁体   English

在WPF GridView中查找单击元素的索引

[英]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. 我有一个GridView元素,我想在单击其中一个元素时执行一些操作。 So I set ItemClick property of the GridView to TopicsPage_ItemClick and implement the method. 因此,我将GridView的ItemClick属性设置为TopicsPage_ItemClick并实现了该方法。 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 . 但是上面的每个解决方案都会抛出带有index = -1 ArgumentOutOfRangeException I have exactly the same solution on another page, where I have buttons in GridView and implement Click of them, and it works there. 我在另一页上有完全相同的解决方案,在GridView中有按钮,并实现了Click ,并且在那里可以正常工作。 Any advice would be apprecitated. 任何建议将不胜感激。

Gonna assume your GridView ItemsSource is bind to a collection. 假设您的GridView ItemsSource已绑定到集合。

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. 这是我的经验,如果您具有IsItemClickEnabled="True"ItemClick事件将触发,但SelectionChanged将不触发,而SelectedIndex为-1。

To get the index you can you grab it by casting it from the IndexOf 要获取索引,您可以通过从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 如果愿意,也可以从GridView.ItemsSource collection.IndexOf中获取它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM