按钮在GridView:我怎么知道哪个项目
本文关键字:项目 我怎么知道 GridView 按钮 | 更新日期: 2023-09-27 18:07:53
我想在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?
单击的Button
的DataContext
将是您要查找的项目
假设你的源类是Calibration
private void OnStart(object sender, RoutedEventArgs e)
{
Button button = sender as Button;
Calibration clickedCalibration = button.DataContext as Calibration;
// ...
}
另一种方法是使用Command
而不是Click事件。这将允许你像这样绑定CommandParameter
<Button Command="{Binding MyCommand}"
CommandParameter="{Binding}"/>
这样的例子可以在网上找到,这里有一个:将命令参数传递给RelayCommand
如何在GridView上使用OnSelectedIndexChanged更改事件?
public void Grid_selectedIndexChanged(Object sender, EventArgs e)
{
GridViewRow row = Grid.SelectedRow;
}