user1123530
user1123530

Reputation: 561

Get binding object from Tap event

I'm trying to access the object that I bound a DataTemplate to, specifically I only need one int value. I've linked the main Grid from within the DataTemplate to an event handler via Tap:

<DataTemplate x:Name="joinTemplate">
  <Grid Tag="{Binding index}" DataContext="{Binding}" Tap="select_Click" ...>
    ...
  </Grid>
</DataTemplate>

My handler looks like:

private void select_Click(object sender, System.Windows.Input.GestureEventArgs e)

The problem is that I still can't access sender.DataContext or sender.Tag. However, when I run it in the debugger and look at it through Watch, I can get to both the DataContext and Tag by simply expanding "base" twice. That should mean that the object that I'm being given inherits those objects and is somehow the child of the original Grid, however, I thought that the sender was always the Grid you bound the handler to? To get the actual element that I tapped I'd have to use, for this example, e.OriginalSource, right?

Upvotes: 4

Views: 2337

Answers (1)

Kevin Gosse
Kevin Gosse

Reputation: 39007

Just cast sender to the appropriate type to access the DataContext property:

((FrameworkElement)sender).DataContext

Then, the same way, you'll have to bind the value to whichever type you binded to the grid. For instance, if you binded an object of type Model:

var model = (Model)((FrameworkElement)sender).DataContext

Upvotes: 11

Related Questions