【问题标题】:how to get the row index in a datagrid wpf according to the button of the row pressed如何根据按下的行的按钮获取datagrid wpf中的行索引
【发布时间】:2016-01-04 15:33:01
【问题描述】:

我在 wpf 中有一个数据网格,每行都有一个编辑按钮。如何获取焦点所在的行索引,即单击编辑按钮的行?

【问题讨论】:

    标签: .net wpf


    【解决方案1】:

    如果您的项目是唯一的,您可以使用 IndexOf(item) 在您的收藏中检索索引。所以,你基本上需要你的物品和你的收藏,然后你就可以走了。

    您可以通过为您的DataGrid 命名,在后面的代码中轻松访问该集合。对于项目,您可以从ButtonDataGridRow 遍历可视化树,然后使用其DataGridRow.Item 属性。

    <DataGrid x:Name="dataGrid1" ItemsSource="{Binding}" AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridTemplateColumn Header="Button Column">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <Button Click="Button_Click" Content="Edit"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>
    

    我假设网格的DataContext 是项目集合。

    在后面的代码中,处理Button_Click 事件。我使用辅助方法递归查找DataGridRow

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        var row = GetParent<DataGridRow>((Button)sender);
        var index = dataGrid1.Items.IndexOf(row.Item);
        MessageBox.Show("Index = " + index, "Clicked Value");
    }
    
    private TargetType GetParent<TargetType>(DependencyObject o)
        where TargetType : DependencyObject
    {
        if (o == null || o is TargetType) return (TargetType)o;
        return GetParent<TargetType>(VisualTreeHelper.GetParent(o));
    }
    

    这应该会给你一个消息框,显示你的列的索引。

    但是,在大多数情况下,人们实际上并不需要索引,而是希望访问索引后面的项目。在这种情况下,忘记IndexOf 部分,直接使用row.Item

    【讨论】:

      猜你喜欢
      • 2014-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-24
      • 2016-03-28
      • 1970-01-01
      • 1970-01-01
      • 2018-09-16
      相关资源
      最近更新 更多