【问题标题】:Get Selected Items from a GridView从 GridView 获取选定项目
【发布时间】:2016-03-16 01:36:05
【问题描述】:

我有一个像这样的 GridView:

<GridView x:Name="MyGrid" ItemsSource="{x:Bind Wallpapers}" SelectionMode="Multiple">
    <GridView.ItemTemplate>
        <DataTemplate x:DataType="data:ImageItem">
            <Image Width="150" Height="150" Source="{x:Bind img}" Tag="{x:Bind TagIndex}"/>
        </DataTemplate>
    </GridView.ItemTemplate>
</GridView>

我需要获取选定的 Image 控件以获取它们的 Tag 属性。 我试过这样:

foreach (Image img in MyGrid.SelectedItems)
{
    int index = img.Tag as int;
}

但我得到 System.InvalidCastException。我该怎么做?

【问题讨论】:

  • 你的调试器在运行时告诉你Tag属性的类型是什么?
  • 它在 foreach 行上给了我 System.InvalidCastException。 tag 属性正确设置为 int
  • 执行代码可能会告诉你,但使用调试器应该会告诉你为什么。我总是建议在抛出时打破所有 CLR 异常
  • 在尝试将 MyGrid.SelectedItems 转换为 Image 时不会停止调试。它只告诉我 SelectedItems 是 System._ComObject 类型

标签: gridview uwp windows-10-mobile


【解决方案1】:

编辑:删除旧答案。

试试这样的

foreach(var item in MyGrid.SelectedItems)
{
    var image = item as TheTypeInItemsSource;//This is the type you have used in ItemsSource
    int index = image.TagIndex;
}

我现在这台电脑上没有 Win10 来测试它,所以我不确定它是否有效。

GridView 的 SelectedItem 与 ItemsSource 中的 SelectedItem 的类型相同。据我了解,您作为 GridView 的源提供的项目类型包含一个图像和一个整数,即 TagIndex。只需从 Image 控件中获取项目的 TagIndex 而不是 Tag。

【讨论】:

    【解决方案2】:

    您收到 InvalidCast 异常,因为 gridview SelectedItems 集合的成员与 gridview ItemsSource 属性绑定到的集合中的项目(给定示例中的 ImageItem)具有相同的类型。

    因此,可以使用以下代码直接获取标签索引:

    foreach (ImageItem imgItem in MyGrid.SelectedItems)
    {
        int index = imgItem.TagIndex;
    }
    

    或者使用 var 关键字:

    foreach (var imgItem in MyGrid.SelectedItems)
    {
        var index = imgItem.TagIndex;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-27
      • 2023-03-18
      • 1970-01-01
      相关资源
      最近更新 更多