繁体   English   中英

如何获取WPF Datagrid的行索引?

[英]How to get the row index of a WPF Datagrid?

我在wpf datagrid中使用图像控制列。 如果单击,该控件用于删除datagrid中的行。任何人都可以告诉我如何冒泡控件click事件以选择网格的整行。 以下是我现在的代码。

XAML代码:

  <DataGrid x:Name="dg" >
  <DataGrid.Columns>
 <DataGridTextColumn Header="ID"  Binding="{Binding Path=ZoneId}" />
<DataGridTextColumn Header="Sector" Binding="{Binding Path=SectorIds"/>
  <DataGridTemplateColumn Width="40">
     <DataGridTemplateColumn.CellTemplate >
              <DataTemplate>                                     
       <Image x:Name="imgDel"   Source="Delete.png" Stretch="None" MouseLeftButtonDown="imgDel_MouseLeftButtonDown" />
             </DataTemplate>                                    
            </DataGridTemplateColumn.CellTemplate>
           </DataGridTemplateColumn>
     </DataGrid.Columns>
    </DataGrid>

代码背后:

private void imgDel_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{            
       var inx = dg.SelectedIndex;
}

我的要求是当我单击行中的图像控件时,它应该从datacontrol中删除整行。 我的数据网格与一个集合绑定。

谢谢

您有sender您可以使用它来获取行索引。

我有一个实用工具方法,我用来获取网格行/列。

public static Tuple<DataGridCell, DataGridRow> GetDataGridRowAndCell(DependencyObject dep)
{
    // iteratively traverse the visual tree
    while ((dep != null) && !(dep is DataGridCell) && !(dep is DataGridColumnHeader))
    {
        dep = VisualTreeHelper.GetParent(dep);
    }

    if (dep == null)
        return null;

    if (dep is DataGridCell)
    {
        DataGridCell cell = dep as DataGridCell;

        // navigate further up the tree
        while ((dep != null) && !(dep is DataGridRow))
        {
            dep = VisualTreeHelper.GetParent(dep);
        }

        DataGridRow row = dep as DataGridRow;

        return new Tuple<DataGridCell, DataGridRow>(cell, row);
    }

    return null;
}

可以像这样调用:

private void OnDoubleClick(object sender, MouseButtonEventArgs e)
        {
            DependencyObject dep = (DependencyObject)e.OriginalSource;

            Tuple<DataGridCell, DataGridRow> tuple = GetDataGridRowAndCell(dep);
        }

如果您正在尝试获取图像所在的DataGridRow对象的引用,则可以使用VisualTreeHelper来查找它。

private void imgDel_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{            
     DependencyObject dataGridRow = sender as DependencyObject;
     while (dataGridRow != null && !(dataGridRow is DataGridRow)) dataGridRow = VisualTreeHelper.GetParent(dataGridRow);
     if (dataGridRow!= null)
     {
           // dataGridRow now contains a reference to the row,
     }    
}

暂无
暂无

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

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