2016-11-16 60 views
0

我有一個datagrid,第一列單元格綁定到一個文本框。當綁定的文本框具有焦點時,我想要獲取數據網格的整行內容。我可以用GotFocus觸發事件,但是因爲在DataGrid中沒有選擇任何東西,所以我不知道哪一行正在被「編輯」。有任何想法嗎?當DatagridTemplateColumn.CellTemplate是一個文本框時如何獲取datagrid行

<DataGrid x:Name="buildDataGrid" 
      ItemsSource="{Binding BuildData}" 
      AutoGenerateColumns="False" 
      CanUserReorderColumns="False" 
      CanUserSortColumns="False" 
      CanUserResizeRows="False" 
      SelectionUnit="CellOrRowHeader" 
      CanUserAddRows="False" 
      CanUserDeleteRows="False" 
      Margin="0,0,10,0"> 
    <DataGrid.Columns> 
     <DataGridTemplateColumn Header="Serial Number" 
           MinWidth="200" 
           Width="*" 
           x:Name="componentSerialNumberDataGridTemplate"> 
      <DataGridTemplateColumn.CellTemplate> 
       <DataTemplate> 
        <TextBox Text="{Binding SerialNumber, UpdateSourceTrigger=PropertyChanged}" 
          x:Name="snoTextBox" 
          BorderThickness="0" 
          Focusable="True" 
          GotFocus="snoTextBox_GotFocus"> 
         <TextBox.InputBindings> 
          <KeyBinding Command="{Binding SerialNumberEnterCommand}" 
             CommandParameter="{Binding Path=Text, ElementName=snoTextBox}" 
             Key="Return"/> 
         </TextBox.InputBindings> 
        </TextBox> 
       </DataTemplate> 
      </DataGridTemplateColumn.CellTemplate> 
     </DataGridTemplateColumn> 

     <DataGridTextColumn Header="Part Number" 
          Binding="{Binding ComponentNumber}" 
          CanUserReorder="False" 
          MinWidth="200" 
          IsReadOnly="True" 
          CanUserResize="True" /> 
     <DataGridTextColumn Header="Description" 
          Binding="{Binding ComponentName}" 
          CanUserReorder="False" 
          Width="Auto" 
          MinWidth="400" 
          IsReadOnly="True" 
          CanUserResize="True" /> 
    </DataGrid.Columns> 
</DataGrid> 
+1

你試過嗎? http://blog.scottlogic.com/2008/12/02/wpf-datagrid-detecting-clicked-cell-and-row.html –

+1

謝謝,它的工作,我發佈瞭解決方案。 – Steven

回答

0

感謝Devlin Carnate,我指出了正確的方向並找到了解決方案!

private void snoTextBox_GotFocus(object sender, RoutedEventArgs e) 
     { 
      DependencyObject dep = (DependencyObject)e.OriginalSource; 

      // iteratively traverse the visual tree 
      while ((dep != null) && !(dep is DataGridCell) && !(dep is System.Windows.Controls.Primitives.DataGridColumnHeader)) 
      { 
       dep = VisualTreeHelper.GetParent(dep); 
      } 

      if (dep == null) 
       return; 

      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; 
       if (row != null) 
       { 
        ComponentData cd = row.DataContext as ComponentData; 
        statusMessage(cd.ComponentNumber); 
       } 
      } 
     } 
相關問題