WPF DataGrid两行无法显示不同值的问题求助
修复最初的代码生成模板方案
你之前尝试直接修改可视化树导致空引用,是因为DataGrid添加Items后不会立即渲染所有单元格,UI线程还没完成布局时GetCellContent会返回null。正确的做法是用数据绑定,给每行提供不同的数据源:
- 定义数据模型:
public class CoachRow { public string[] CoachNumbers { get; set; } }
- 修改CreateCoachCompositionDataGrid方法:
private void CreateCoachCompositionDataGrid() { dataGridCoachComposition.Columns.Clear(); dataGridCoachComposition.Margin = new Thickness(16, 468, 230, 18); dataGridCoachComposition.HeadersVisibility = DataGridHeadersVisibility.None; dataGridCoachComposition.RowHeight = 50; dataGridCoachComposition.VerticalAlignment = VerticalAlignment.Top; // 创建14列,每列绑定到CoachNumbers数组的对应索引 for (int i = 0; i < 14; i++) { DataGridTemplateColumn column = new DataGridTemplateColumn(); column.Width = new DataGridLength(1, DataGridLengthUnitType.Star); DataTemplate cellTemplate = new DataTemplate(); FrameworkElementFactory stackPanel = new FrameworkElementFactory(typeof(StackPanel)); stackPanel.SetValue(StackPanel.OrientationProperty, Orientation.Vertical); // 绑定到当前行CoachNumbers的第i个元素 FrameworkElementFactory textBlock = new FrameworkElementFactory(typeof(TextBlock)); textBlock.SetBinding(TextBlock.TextProperty, new Binding($"CoachNumbers[{i}]")); textBlock.SetValue(TextBlock.HorizontalAlignmentProperty, HorizontalAlignment.Center); stackPanel.AppendChild(textBlock); FrameworkElementFactory comboBox = new FrameworkElementFactory(typeof(ComboBox)); comboBox.SetValue(ComboBox.ItemsSourceProperty, new string[] { "ENG", "HIN" }); comboBox.SetValue(FrameworkElement.MarginProperty, new Thickness(5)); stackPanel.AppendChild(comboBox); cellTemplate.VisualTree = stackPanel; column.CellTemplate = cellTemplate; dataGridCoachComposition.Columns.Add(column); } // 添加两行数据 dataGridCoachComposition.Items.Add(new CoachRow { CoachNumbers = Enumerable.Range(1, 14).Select(n => $"C{n:D2}").ToArray() }); dataGridCoachComposition.Items.Add(new CoachRow { CoachNumbers = Enumerable.Range(15, 14).Select(n => $"C{n:D2}").ToArray() }); }
这种方式通过数据绑定让UI自动匹配数据,避免了直接操作可视化树的问题,也更易维护。
为什么之前的修改会抛NullReferenceException?
GetCellContent返回null是因为DataGrid的单元格渲染是延迟的,添加Items后UI线程需要时间完成布局和可视化元素的创建。即使使用Dispatcher,也可能因为布局尚未完成导致获取不到元素。直接操作可视化树是WPF中的反模式,推荐始终用数据绑定处理动态内容。
内容的提问来源于stack exchange,提问作者SEIL
相关产品推荐
相关产品推荐

