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

WPF中Telerik RadGridView通过XAML绑定ItemsSource不显示数据求解

问题原因
  • 缺少DataContext配置:WPF的XAML绑定默认会从控件的DataContext属性中查找绑定的属性名,你没有为窗口设置DataContext,绑定无法定位到MyProperties1、MyProperties2两个属性
  • 属性初始化时机与变更通知缺失:你在InitializeComponent()执行完成后才对两个集合属性赋值,而这两个属性是普通CLR属性,没有实现INotifyPropertyChanged接口,赋值后无法通知UI更新,绑定拿到的始终是初始的null值
修复方案

快速修复(适配现有代码)

仅修改MainWindow构造函数即可:

public MainWindow()
{
    // 先初始化集合属性,保证界面初始化时可以拿到有效值
    MyProperties1 = new List<MyGridView1Data>();
    MyProperties1.Add(new MyGridView1Data());

    MyProperties2 = new List<MyGridView2Data>();
    MyProperties2.Add(new MyGridView2Data());

    InitializeComponent();
    // 核心配置:将窗口自身设为绑定的数据源
    this.DataContext = this;
}

规范实现(符合WPF绑定最佳实践)

如果后续需要动态修改集合内容或属性值,建议按标准MVVM模式调整:

  1. 实现INotifyPropertyChanged接口,保证属性变更可通知UI
  2. 用ObservableCollection<T>替代List<T>,保证集合元素增减时UI自动同步
    修改后的代码示例:
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;

public partial class MainWindow : Window, INotifyPropertyChanged
{
    // 实现属性变更通知
    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    private ObservableCollection<MyGridView1Data> _myProperties1;
    public ObservableCollection<MyGridView1Data> MyProperties1
    {
        get => _myProperties1;
        set { _myProperties1 = value; OnPropertyChanged(); }
    }

    private ObservableCollection<MyGridView2Data> _myProperties2;
    public ObservableCollection<MyGridView2Data> MyProperties2
    {
        get => _myProperties2;
        set { _myProperties2 = value; OnPropertyChanged(); }
    }

    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = this;

        // 此时即使在InitializeComponent之后赋值也能正常通知UI更新
        MyProperties1 = new ObservableCollection<MyGridView1Data>();
        MyProperties1.Add(new MyGridView1Data());

        MyProperties2 = new ObservableCollection<MyGridView2Data>();
        MyProperties2.Add(new MyGridView2Data());
    }
}
补充说明

直接在后置代码给ItemsSource赋值可以正常运行,是因为直接对控件的依赖属性赋值,不需要走绑定的数据源查找和变更通知逻辑,因此不受上述两个问题影响。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 00:06:03