Brian Hamill
Brian Hamill

Reputation: 2596

UWP Get Clicked Item in DataTemplate

I'm sure this has been asked before, however I cannot find the appropriate answer.

I am using an ItemTemplate to display a list of users, this list consists of StackPanels with user details. How can I get the user object that I clicked on?

Current code:

<GridView Name="usersList">
    <GridView.ItemTemplate>
        <DataTemplate>
            <StackPanel PointerPressed="UserClicked">
                <TextBlock Text="{Binding Forename}"/>
                <TextBlock Text="{Binding Surname}"/>
            </StackPanel>
        </DataTemplate>
    </GridView.ItemTemplate>
</GridView>

This is being populated via an async API call:

usersList.ItemsSource = null;
var task = Users.UserAsync<User>();
usersList.ItemsSource = await task;

How can I capture the User object that has been clicked on PointerPressed?

Upvotes: 2

Views: 1286

Answers (2)

A. Milto
A. Milto

Reputation: 2383

Like this:

    private void UserClicked(object sender, PointerRoutedEventArgs e)
    {
        User clickedOnUser = (sender as StackPanel).DataContext as User;
    }

This approach is more direct than the one using usersList.SelectedItem, so I recommend sticking with it. E.g., it will work if you set SelectionMode="None" for the GridView, whereas the approach based on usersList.SelectedItem won't.

Also, as Sean O'Neil rightfully noticed, you might want to use Tapped event instead of PointerPressed for the most general case scenario.

Upvotes: 2

Sean O&#39;Neil
Sean O&#39;Neil

Reputation: 1241

Use GridView.SelectedItem to reference the object you want when you click on it.

private void UserClicked_PointerPressed(object sender, PointerRoutedEventArgs e)
   {
     var whatYouWant = usersList.SelectedItem;
   }

Upvotes: 0

Related Questions