I have a GridView like this:
<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>
I need to get selected Image controls to obtain their Tag property. I tried like this:
foreach (Image img in MyGrid.SelectedItems)
{
int index = img.Tag as int;
}
But I get System.InvalidCastException. How can I do that?
You receive an InvalidCast exception because the members of the gridview SelectedItems collection are of the same type as the items in the collection to which the gridview ItemsSource property is bound (ImageItem in the given example).
Therefore, the following code could be used to get the tag index directly:
foreach (ImageItem imgItem in MyGrid.SelectedItems)
{
int index = imgItem.TagIndex;
}
Or using the var keyword:
foreach (var imgItem in MyGrid.SelectedItems)
{
var index = imgItem.TagIndex;
}