Search code examples
c++xamluwpwinrt-xamlc++-winrt

How to determine the clicked item in a grid view


Given a GridView such as

<GridView IsItemClickEnabled="True"  ItemClick="favorite_clicked" ItemsSource="{x:Bind MainViewModel.FavoriteBinders}" Grid.Column="1">
    <GridView.ItemTemplate>
        <DataTemplate   x:DataType="local:FavoriteBinder">
            <StackPanel AccessKey="{x:Bind CedictId, Mode=OneWay}"  Width="200" Margin="20">
            <TextBlock   Text="{x:Bind Simplified, Mode=OneWay}" FontWeight="Bold" 
              />
            <TextBlock Text="{x:Bind Pinyin, Mode=OneWay}" TextWrapping="NoWrap" 
                />
        </StackPanel>
    </DataTemplate>
</GridView.ItemTemplate>
<GridView.ItemsPanel>
    <ItemsPanelTemplate>
            <ItemsWrapGrid MaximumRowsOrColumns="7"/>
    </ItemsPanelTemplate>
</GridView.ItemsPanel>

Which is populated with a typeFavoriteBinder that has a int32_t field called id.

And a click function that looks like:

void FavoritesPage::favorite_clicked(
    Windows::Foundation::IInspectable const& sender, 
    Windows::UI::Xaml::RoutedEventArgs const& args) 
{
}

How can I get the id of the item clicked in the favorite_clicked function?


Solution

  • In favorite_clicked event, you can get the FavoriteBinder class you click by e.ClickedItem() method, and use .as method to convert the object to FavoriteBinder type.

    void FavoritesPage::favorite_clicked(IInspectable const& sender, winrt::Windows::UI::Xaml::Controls::ItemClickEventArgs const& e)
    {
        WinrtText::FavoriteBinder clickVM = e.ClickedItem().as< WinrtText::FavoriteBinder >();
        int32_t clickId = clickVM.CedictId();
    }