You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF DataGrid绑定异常:列头生成但无数据项显示

问题分析与解决方案

可能的问题点及对应解决方法:


1. 确认DataContext是否正确绑定

你的OpenContributioWindow方法中创建了ViewModel实例vm并调用Anzeigen<contributionWindow>(),但需要确保该方法将ViewModel正确设置为窗口的DataContext。如果Anzeigen方法未处理此事,需手动添加绑定逻辑:

public void Anzeigen<TWindow>() where TWindow : Window, new()
{
    var window = new TWindow();
    window.DataContext = this; // 将当前ViewModel实例设为窗口的DataContext
    window.Show();
}

或者在窗口构造函数中指定DataContext:

public contributionWindow(Anwendung viewModel)
{
    InitializeComponent();
    DataContext = viewModel;
}

2. 将Betrag从结构体(struct)改为类(class)

WPF绑定系统对值类型(struct)的支持存在局限性,当值类型作为集合项时,容易出现数据不显示的问题。将Betrag改为引用类型即可解决此问题:

/// <summary>
/// class to serve as single entry for the Bewohner object
/// </summary>
public class Betrag
{
    /// <summary>
    /// Category string of Betrag
    /// </summary>
    public string kategorie { get; set; }

    /// <summary>
    /// Amount in decimal of Betrag
    /// </summary>
    public decimal wert { get; set; }

    /// <summary>
    /// constructor for the Betrag Class
    /// </summary>
    /// <param name="k"></param>
    /// <param name="w"></param>
    public Betrag(string k, decimal w)
    {
        kategorie = k;
        wert = w;
    }
}

3. 修正BeitragsListe的属性setter

ObservableCollection<T>本身已实现INotifyCollectionChanged接口,替换整个集合时仅需触发PropertyChanged通知即可,手动调用OnCollectionChanged反而会干扰绑定逻辑:

public ObservableCollection<Betrag> BeitragsListe
{
    get => this._BeitragsListe;
    set
    {
        this._BeitragsListe = value;
        OnPropertyChanged();
        Log.WriteLine($"{BeitragsListe.GetType().Name} has changed");
    }
}

验证步骤

  1. 确认窗口的DataContext指向正确的ViewModel实例
  2. 将Betrag改为class后重新编译运行
  3. 检查BeitragsListe的setter逻辑是否修正

完成以上操作后,DataGrid即可正常显示集合中的数据项。

内容的提问来源于stack exchange,提问作者FlorianD

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 12:15:12