2014-02-17 71 views
0

我在wpf datagrid中使用图像控制列。 该控件用于删除datagrid中的行(如果单击)。可以让任何人告诉我如何控制单击事件以选择整个网格行。以下是我目前的代码。如何获取WPF Datagrid的行索引?

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; 
} 

我的要求是,当我点击了排在图像控制,应该从数据控件删除整个行。我的数据网格绑定了一个集合。

感谢

回答

0

如果你想获得的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, 
    }  
} 
1

你有sender,你可以用它来得到你的行索引。

+0

谢谢...但发件人将是我的Image控件。 – Prabhakaran

+0

在这种情况下 - 你可以通过'dg.CurrentColumn.DisplayIndex'检索'dg.SelectedIndex'行和列 - 看到这个职位 - http://stackoverflow.com/questions/5978053/datagrid-how-to-get-在-currentcell的最-将selectedItem – Sadique

1

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

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); 
     } 
相关问题