GridView中的按钮:我如何知道哪个项目?

时间:2011-09-05 15:24:53

标签: c# wpf gridview binding

我想在GridView的每一行中都有一个按钮来对此行执行操作。我能够获得点击,但如何确定此按钮属于哪一行?

我现在所拥有的是:

        <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
    }

是否有某种方法可以将此行上的项目绑定到RoutedEventArgs?

2 个答案:

答案 0 :(得分:5)

点击的DataContext的{​​{1}}将是您要查找的项目

假设您的源类是Button

Calibration

另一种方法是使用private void OnStart(object sender, RoutedEventArgs e) { Button button = sender as Button; Calibration clickedCalibration = button.DataContext as Calibration; // ... } 代替Click事件。这将允许您像这样绑定Command

CommandParameter

这方面的例子可以在网上找到,这里有一个:Pass Command Parameter to RelayCommand

答案 1 :(得分:0)

如何在GridView上使用OnSelectedIndexChanged已更改事件?

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