UWP: how to get the RightTapped GridView Item

后端 未结 2 1825
隐瞒了意图╮
隐瞒了意图╮ 2021-01-28 08:21

I have a GridView like below



        
2条回答
  •  -上瘾入骨i
    2021-01-28 08:57

    If the SymbolControl in your ItemTemplate is a bit more complex and the elements in it may have their own DataContexts you could get a reference to the parent ListViewItemPresenter using the following helper method and then cast the DataContext of this to your Symbol item:

    private void SymbolGridView_RightTapped(object sender, RightTappedRoutedEventArgs e)
    {
        ListViewItemPresenter lvi = e.OriginalSource as ListViewItemPresenter;
        if (lvi == null)
            lvi = FindParent(e.OriginalSource as DependencyObject);
    
        if (lvi != null)
        {
            SymbolItem clickedItem = lvi.DataContext as SymbolItem;
            if (clickedItem != null)
                MyMediaElement.Source = new Uri(this.BaseUri, symbolItem.ExampleAudio);
        }
    }
    
    private static T FindParent(DependencyObject dependencyObject) where T : DependencyObject
    {
        var parent = VisualTreeHelper.GetParent(dependencyObject);
    
        if (parent == null) return null;
    
        var parentT = parent as T;
        return parentT ?? FindParent(parent);
    }
    

提交回复
热议问题