简体   繁体   English

GridView中的按钮:我怎么知道哪个项目?

[英]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. 我想在GridView的每一行中都有一个按钮来对此行执行操作。 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? 是否可以通过某种方式将此行上的项目绑定到RoutedEventArgs?

The DataContext of the clicked Button will be the item you are looking for 单击ButtonDataContext将是您要查找的项目

Assuming your source class is Calibration 假设您的源类别是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. 另一种方法是使用Command而不是Click事件。 This would allow you to bind CommandParameter like this 这将允许您像这样绑定CommandParameter

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

Examples of this can be found all over the net, here is one: Pass Command Parameter to RelayCommand 可以在网上找到这样的示例,这是一个示例 :将Command参数传递给RelayCommand

How about using an OnSelectedIndexChanged changed event on your GridView? 如何在GridView上使用OnSelectedIndexChanged更改的事件?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM