Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 595
user1123530 Avatar asked Dec 21 '22 02:12

user1123530


1 Answers

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
like image 73
Kevin Gosse Avatar answered Dec 31 '22 10:12

Kevin Gosse