2014-02-17 70 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); 
     } 
相關問題