DataGrid: Help accessing a control defined in a CellEditingTemplate

主宰稳场 提交于 2020-01-04 12:14:42

问题


I am using the WPF DataGrid with a DataGridTemplateColumn. The DataGridTemplateColumn.CellEditingTemplate contains a ComboBox with IsEditable set to 'true'. In my RowEditEnding event handler, I'd like to read the Text property of that ComboBox - the only problem is that I don't know how to retrieve the ComboBox instance within the event handler in order to get to the Text property.

For reference, here's my DataTemplate:

  <!-- ... -->
  <my:DataGridTemplateColumn.CellEditingTemplate>
      <DataTemplate>
          <ComboBox IsEditable="True" ItemsSource="{Binding Source={StaticResource ProductCategories}}" SelectedItem="{Binding Path=Name}" DisplayMemberPath="Name" />
      </DataTemplate>
  </my:DataGridTemplateColumn.CellEditingTemplate>
  <!-- ... -->

And my code:

    private void productsDataGrid_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
    {
        // UH-OH! Where do I find the ComboBox instance?
    }

I know that I can get to the current affected row using e.Row... Maybe the solution involves something using e.Row? I've tried walking the visual tree recursively from e.Row down looking for an instance of ComboBox, but no dice. I'm almost positive that the solution is simple, however, I'm relativley new to WPF in general. Any suggestions would be much appreciated.

Thanks!


回答1:


you can get de Combobox Column directly from your DataGrid using this code

var cbx = (DataGridComboBoxColumn)productsDataGrid.Columns.First(a => a.Header.ToString() == "name of your column");



回答2:


It seems access to the CellEditingTemplate is only available during the PreparingCellForEdit event in the DataGrid. You could wire up a hander for that event on the DataGrid and do something like this on the handler to get to your ComboBox

private void _CounterGoalsGrid_PreparingCellForEdit(object sender, 
    DataGridPreparingCellForEditEventArgs e) 
    {
        ComboBox editCombo = (e.EditingElement.FindName("<your combobox name>") as ComboBox);
    }
  • Remember to name your ComboBox in xaml.


来源:https://stackoverflow.com/questions/739084/datagrid-help-accessing-a-control-defined-in-a-celleditingtemplate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!