有时候我们需要选择一个 GridView 的一项,通过我们右击。

于是我们需要在 GridView 的 SelectionMode 为 Single ,IsRightTapEnabled 为True

假如我们给的 ItemSsource 的类型是List<Student>,那我们可以通过简单方法得到右击的 Student 。

我们需要使用 RightTapped

      <GridView x:Name="SymbolGridView"
         SelectionMode="Single"
         IsItemClickEnabled="True"
         IsRightTapEnabled="True"
         ItemsSource="{x:Bind View.Student}"
         ItemClick="SymbolGridView_OnItemClick"
         RightTapped="SymbolGridView_OnRightTapped">
            <GridView.ItemTemplate>
                <DataTemplate x:DataType="view:ViewModel">
                    <TextBlock Text="{Binding Name}"></TextBlock>
                    </DataTemplate>
            </GridView.ItemTemplate>
        </GridView>

注意 DataTemplate 的是 TexTblock

我们通过

        private void SymbolGridView_OnRightTapped(object sender, RightTappedRoutedEventArgs e)
        {
            var student = (e.OriginalSource as TextBlock)?.DataContext as Student;
        }

就可以得到 Student

注意e.OriginalSource就是我们刚才使用的 DatEtemplate 的 TexTblock ,我们在 DateTemplate 使用类型 Type ,那么 OriginalSource 就可以使用 Type 。拿到后,他的 DataContext 就是我们选择的。

如果使用个人控件(UserControl),那么请要有 DataContext ,不要覆盖。

这样我们就可以得到 GridViewItem

但有时候, OriginalSource 是 ListViewItemPresenter ,我们可以用一个简单方法,使用 FrameworkElement

我们修改代码

 var student = (e.OriginalSource as FrameworkElement)?.DataContext as Student;

这样我们就可以得到,不需要去看 DataTemplate


本文会经常更新,请阅读原文: https://blog.lindexi.com/post/win10-uwp-%E5%8F%B3%E5%87%BB%E9%80%89%E6%8B%A9-GridViewItem.html ,以避免陈旧错误知识的误导,同时有更好的阅读体验。

如果你想持续阅读我的最新博客,请点击 RSS 订阅,推荐使用RSS Stalker订阅博客,或者前往 CSDN 关注我的主页

知识共享许可协议 本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。欢迎转载、使用、重新发布,但务必保留文章署名林德熙(包含链接: https://blog.lindexi.com ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。如有任何疑问,请 与我联系

无盈利,不卖课,做纯粹的技术博客

以下是广告时间

推荐关注 Edi.Wang 的公众号

欢迎进入 Eleven 老师组建的 .NET 社区

以上广告全是友情推广,无盈利