Button in GridView: how to find out which element?

I want to have a button in each row of the GridView to perform actions on this row. I can get a click, but how to determine which line this button belongs to?

What I have at the moment:

        <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 any way to bind an element of this string to RoutedEventArgs?

+5
source share
2 answers

DataContextpressed Buttonwill be the item you are looking for

Assuming your source class Calibration

private void OnStart(object sender, RoutedEventArgs e)
{
    Button button = sender as Button;
    Calibration clickedCalibration = button.DataContext as Calibration;
    // ...
}

Another way is to use the CommandClick event instead. This will allow you to bind CommandParameteras follows

<Button Command="{Binding MyCommand}"
        CommandParameter="{Binding}"/>

, : RelayCommand

+5

OnSelectedIndexChanged GridView?

public void Grid_selectedIndexChanged(Object sender, EventArgs e)
{
    GridViewRow row = Grid.SelectedRow;
}
0

All Articles