【问题标题】:Is there a way to get clicked item from a GridView as an UI element in WinUI?有没有办法从 GridView 中获取单击的项目作为 WinUI 中的 UI 元素?
【发布时间】:2022-11-22 01:18:34
【问题描述】:

情况描述

我的主页上有一个GridView,其中包含绑定到类列表/数组的项目。

<GridView x:Name="ImageListBox" ItemsSource="{x:Bind displayedImages}" ItemClick="ImageListBox_ItemClick">
   <GridView.ItemTemplate>
       <DataTemplate x:DataType="data:DisplayedImage">
           <Border>
               <Image x:Name="ImageBoxMain" Source="{x:Bind ImagePath }"/>
           </Border>
       </DataTemplate>
   </GridView.ItemTemplate>
</GridView>

每个项目显示从 web json 获取的链接下载的图像(其中的内容经常更改)。

通过单击网格中的其中一张图像,应用程序会导航到一个新页面,该页面显示同一图像的更大版本以及图像的更多细节。

我希望达到的目标

因此,我希望使用ConnectedAnimation 将图像从GridView 中的小版本动画化为新页面中显示的大版本。

根据ConnectedAnimation上的documentation,我需要指定SourceImage才能建立动画连接。

我试过什么

基于documentation,我将以下代码放在GridView 项目点击处理程序中:

ConnectedAnimationService.GetForCurrentView()
      .PrepareToAnimate("forwardAnimation", ImageBoxMain);

问题

我遇到的问题是我没有SourceImage。我的图像是 GridView 的一部分,但我没有设法将图像指定为 UIElement,这是 ConnectedAnimation API 所期望的。

在上面的 XAML 代码 sn-p 中,我们可以看到实际的图像元素被命名为 ImageBoxMain,但是它不能从后面的代码访问,如下图所示:

The type or namespace name 'ImageBoxMain' could not be found

问题

那么,我怎样才能从 GridView 获取点击项目作为 UIElement

【问题讨论】:

    标签: c# winui-3


    【解决方案1】:

    在 GridView 的 XAML 中,确保 IsItemClickEnabled 属性设置为“True”。

    在您的页面中,声明一个成员变量来存储点击的项目:

    private GridViewItem _clickedItem;
    

    在您的 ImageListBox_ItemClick 方法中存储单击的项目并导航:

    private void ImageListBox_ItemClick(object sender, ItemClickEventArgs e)
    {
        _clickedItem = (GridViewItem)ImageListBox.ContainerFromItem(e.ClickedItem);
        Frame.Navigate(typeof(BlankPage2), null, new SuppressNavigationTransitionInfo());
    }
    

    由于 GridViewItem 继承自 UIElement,您可以将其用作 ConnectedAnimation 的源:

    protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
        {
            if (_clickedItem != null)
            {
                ConnectedAnimationService.GetForCurrentView().PrepareToAnimate("forwardAnimation", _clickedItem);
            }
    
            base.OnNavigatingFrom(e);
        }
    

    在接下来的页面中,动画的目标元素可以是任何东西(在我用于测试的代码中,它是一个 Rectangle 元素)。

    【讨论】:

      猜你喜欢
      • 2011-07-31
      • 2011-10-20
      • 1970-01-01
      • 2012-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多