Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Button in GridView: How do I know which Item?

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?

like image 563
MTR Avatar asked Sep 05 '11 15:09

MTR


1 Answers

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

like image 62
Fredrik Hedblad Avatar answered Nov 14 '22 17:11

Fredrik Hedblad