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

WPF音乐数据分析应用DataGrid无法显示歌曲数据求助

问题原因与解决方案

核心问题:WPF数据绑定仅支持公共属性,而非字段

你定义的SongData类中所有成员都是公共字段(Field),但WPF的数据绑定系统默认只能识别公共属性(Property),这就是绑定路径找不到对应成员的根本原因。

解决方案:将SongData的字段改为属性

修改SongData类,把所有字段替换为带get/set的公共属性:

public class SongData
{
    public uint Id { get; set; }
    public BitmapImage Cover { get; set; }
    public string Title { get; set; }
    public string Artist { get; set; }
    public string Album { get; set; }
    public TimeSpan Duration { get; set; }
    public TimeSpan Cue { get; set; }
    public string Key { get; set; }
    public bool Available { get; set; }
    public string FilePath { get; set; }
    public decimal Bpm { get; set; }
}

额外优化建议

  • 实现INotifyPropertyChanged接口:如果后续需要修改SongData的属性值并同步到DataGrid,建议让类实现INotifyPropertyChanged接口,确保属性变化能通知UI更新:
public class SongData : INotifyPropertyChanged
{
    private uint _id;
    public uint Id
    {
        get => _id;
        set
        {
            _id = value;
            OnPropertyChanged(nameof(Id));
        }
    }

    // 其他属性按相同逻辑实现...

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
  • 修正列绑定的逻辑一致性:注意到DataGrid中Name列绑定的是FilePath,但类里存在Title属性,可根据需求调整绑定:
<DataGridTextColumn Header="Name" Binding="{Binding Title}" Width="500" CanUserSort="True"/>
  • 格式化TimeSpan显示:默认TimeSpan显示格式不够友好,可通过绑定的StringFormat优化:
<DataGridTextColumn Header="Duration" Binding="{Binding Duration, StringFormat=hh\\:mm\\:ss}" Width="100" CanUserSort="True"/>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 05:54:52