1. 行选中时,.SelectedIndex可以获取行索引
2.单元格选中时,获取行索引可以用以下(Grid为DataGrid的对象)
DataGridCellInfo selectedCell = Grid.SelectedCells.FirstOrDefault();
//没有选中Record
if (selectedCell == null || selectedCell.Column == null)
return;
int index = Grid.Items.IndexOf(selectedCell.Item);
3.替换某个单元格中TextBlock为Combox
DataGridRow row = (DataGridRow)Grid.ItemContainerGenerator.ContainerFromIndex(Index);
DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(row);
//这行代码是通过行得到单元格
DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(Col);
//这行代码是通过index得到具体的单元格
FrameworkElementFactory factory = new FrameworkElementFactory(typeof(StackPanel));
factory.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);
FrameworkElementFactory buttonComboBox = new FrameworkElementFactory(typeof(ComboBox));
buttonComboBox.SetValue(ComboBox.SelectedIndexProperty, 0);
buttonComboBox.SetValue(ComboBox.DisplayMemberPathProperty, "Data");
buttonComboBox.SetValue(ComboBox.ItemsSourceProperty, filterDataList);
buttonComboBox.SetValue(ComboBox.WidthProperty, cell.ActualWidth);
buttonComboBox.SetValue(ComboBox.FontSizeProperty, cell.FontSize - 3);
buttonComboBox.AddHandler(
ComboBox.LoadedEvent,
new RoutedEventHandler(
(s, ea) =>
{
ComboBox comboBox = (ComboBox)s;
comboBox.DropDownClosed += ComboBox_DropDownClosed;
}));
factory.AppendChild(buttonComboBox);
DataTemplate dataTemplate = new DataTemplate();
dataTemplate.VisualTree = factory;
if(cell.ContentTemplate == null)
{
cell.ContentTemplate = dataTemplate;
}
4. ItemContainerGenerator顺序为Datagrid显示的顺序,排序后也与之对应