I want to have a button in each row of a GridView to perform actions on this row. I'm able to get the click, but how do I determine which row this button belongs to?
What I have at the moment is this:
<ListView ItemsSource="{Binding Calibrations}">
<ListView.View>
<GridView>
<GridView.Columns>
<GridViewColumn Header="Voltage [kV]" Width="70" DisplayMemberBinding="{Binding Voltage}" />
<GridViewColumn Header="Filter" Width="100" DisplayMemberBinding="{Binding FilterName}" />
<GridViewColumn Header="Calibration Date" Width="100" DisplayMemberBinding="{Binding CalibrationDate}" />
<GridViewColumn Header="Calibration" Width="60">
<GridViewColumn.CellTemplate>
<DataTemplate>
<Button Content="Start" Click="OnStart" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView.Columns>
</GridView>
</ListView.View>
</ListView>
private void OnStart(object sender, RoutedEventArgs e)
{
// how do I know, on which item this button is
}
Is there maybe some way to bind the item on this row to the RoutedEventArgs?
The DataContext
of the clicked Button
will be the item you are looking for
Assuming your source class is Calibration
private void OnStart(object sender, RoutedEventArgs e)
{
Button button = sender as Button;
Calibration clickedCalibration = button.DataContext as Calibration;
// ...
}
Another way is to use a Command
instead of the Click event. This would allow you to bind CommandParameter
like this
<Button Command="{Binding MyCommand}"
CommandParameter="{Binding}"/>
Examples of this can be found all over the net, here is one: Pass Command Parameter to RelayCommand
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With