c#同时绑定DataGrid WPF

本文关键字:DataGrid WPF 绑定 | 更新日期: 2023-09-27 18:10:23

我试图将ObservableCollection绑定到DataGrid

private void LoadData_Loaded(object sender, RoutedEventArgs e)
{
        ObservableCollection<LoadData> LoadDataSet = new ObservableCollection<LoadData>();
        var items = new List<LoadData>();
        LoadData load = new LoadData("1", "1", "1", "1");
        LoadDataSet.Add(load);
        items.Add(load);
        loadDataGrid.ItemsSource = items;
}
在主窗口

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

DataGrid Name="loadDataGrid" HorizontalAlignment="Left" Margin="373,83,0,0" VerticalAlignment="Top" Height="64" Width="661" Loaded="LoadData_Loaded" /

然后我得到一个异常

类型为"System"的未处理异常。StackOverflowException"发生在xxxx.exe

c#同时绑定DataGrid WPF

虽然我无法想象你做错了什么,但我可以告诉你如何做正确。只需为您的集合创建一个公共属性:

private ObservableCollection<LoadData> items; 
public ObservableCollection<LoadData> Items
{
    get { return items; }
    set { items = value; NotifyPropertyChanged("Items"); }
}
// Implement INotifyPropertyChanged interface here!!

然后将集合属性绑定到DataGrid.ItemsSource属性:

<DataGrid Name="loadDataGrid" ItemsSource="{Binding Items}" HorizontalAlignment="Left" 
    Margin="373,83,0,0" VerticalAlignment="Top" Height="64" Width="661" />

最后,只需填充您的集合:

Items = new ObservableCollection<LoadData>();
LoadData load = new LoadData("1", "1", "1", "1");
LoadDataSet.Add(load);
Items.Add(load);

根据MSDN Loaded,事件发生在元素布局、呈现和准备交互时。

所以我认为当你从LoadData_Loaded设置DataGridItemSource时,它再次引发DataGridLoaded事件,导致一个不结束的递归,因此你得到StackOverFlow异常。

你可以试试Eldho的建议。不要在LoadData_Loaded中编写代码,而是将其写在函数中,并从类的构造函数调用该函数。像下图:

private void LoadDataInGrid(object sender, RoutedEventArgs e)
{
        ObservableCollection<LoadData> LoadDataSet = new ObservableCollection<LoadData>();
        var items = new List<LoadData>();
        LoadData load = new LoadData("1", "1", "1", "1");
        LoadDataSet.Add(load);
        items.Add(load);
        loadDataGrid.ItemsSource = items;
}
public MainWindow()
{
       InitializeComponent();
       DataContext = this;
       LoadDataInGrid();
}