国内最全IT社区平台 联系我们 | 收藏本站
华晨云阿里云优惠2
您当前位置:首页 > php开源 > php教程 > win10 uwp 右击选择 GridViewItem

win10 uwp 右击选择 GridViewItem

来源:程序员人生   发布时间:2017-02-08 08:48:32 阅读次数:3773次

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

因而我们需要在 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 ,我们可以用1个简单方法,使用 FrameworkElement

我们修改代码

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

这样我们就能够得到,不需要去看 DataTemplate

原文:http://lindexi.oschina.io/lindexi/post/win10-uwp-%E5%8F%B3%E5%87%BB%E9%80%89%E6%8B%A9-GridViewItem/

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

生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠
程序员人生
------分隔线----------------------------
分享到:
------分隔线----------------------------
关闭
程序员人生