绑定到DataGrid的ObservableCollection仅显示空行,如何解决?
解决WPF DataGrid绑定后显示空行的问题
问题原因
你的代码存在三个关键错误导致DataGrid只显示空行:
- WPF数据绑定仅支持属性(Property),但实体类
FieldsDataGrid使用的是公共字段(Field) - XAML中Teil列的绑定目标写错了:绑定的是不存在的
Titel,而非实体类中的Teil - 绑定的
ocEingaben是字段而非公共属性,WPF绑定引擎无法正确访问
修复方案
1. 实体类字段改属性
WPF绑定要求绑定目标是带get/set访问器的属性,修改FieldsDataGrid类:
// 基础版本(仅支持初始绑定,不支持数据更新通知) public class FieldsDataGrid { public string Teil { get; set; } public decimal Preis { get; set; } } // 进阶版本(实现INotifyPropertyChanged,支持数据更新后自动刷新UI) public class FieldsDataGrid : INotifyPropertyChanged { private string _teil; public string Teil { get => _teil; set { _teil = value; OnPropertyChanged(nameof(Teil)); } } private decimal _preis; public decimal Preis { get => _preis; set { _preis = value; OnPropertyChanged(nameof(Preis)); } } public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } }
2. 修正XAML绑定名称错误
将Teil列的绑定路径从Titel改为Teil:
<DataGrid.Columns> <DataGridTextColumn Header="Teil" Binding="{Binding Teil}" Width="*"/> <DataGridTextColumn Header="Preis" Binding="{Binding Preis}" Width="*"/> </DataGrid.Columns>
3. ObservableCollection改为公共属性
将原来的字段ocEingaben改为公共属性,确保绑定引擎能访问:
// 推荐用只读属性,避免外部替换集合实例 public ObservableCollection<FieldsDataGrid> ocEingaben { get; } = new ObservableCollection<FieldsDataGrid>();
同时确保DataContext设置正确(以窗口类为例):
public YourWindow() { InitializeComponent(); DataContext = this; // 如果ocEingaben定义在当前窗口类中 // 若使用MVVM模式,将ViewModel实例赋值给DataContext即可 }
4. 优化数据添加逻辑(可选)
由于ObservableCollection本身会自动通知UI集合变化,不需要每次添加数据后重新设置ItemsSource,可以删除以下代码:
IDGrid.ItemsSource = View.ocEingaben;
确保DataContext正确后,直接调用ocEingaben.Add()就能自动更新DataGrid。
内容的提问来源于stack exchange,提问作者NadiaBallshek
相关产品推荐
相关产品推荐

