【问题标题】:Button in GridView: How do I know which Item?GridView 中的按钮:我如何知道哪个项目?
【发布时间】:2011-11-10 17:17:44
【问题描述】:

我想在 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?

【问题讨论】:

  • 检查 Grid 的选中项属性怎么样?
  • 不知道 WPF,但 asp.net 有一个 OnCommand 事件,您可以指定传递到处理程序的 eventargs 的 CommandName 和 CommandType 参数。

标签: c# wpf gridview binding


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    点击的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}"/>
    

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

    【讨论】:

    • 谢谢,正是我想要的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-08
    相关资源
    最近更新 更多