gpt4 book ai didi

c# - 无法将 ObservableCollection 绑定(bind)到 DataGrid

转载 作者:太空宇宙 更新时间:2023-11-03 10:54:50 25 4
gpt4 key购买 nike

如果我用 C# 编码编写就可以了比如

DataGrid dg = new DataGrid();
dg.AutoGenerateColumns = true;
dg.ItemsSource = db;

数据库在哪里

public ObservableCollection<Data> db = new ObservableCollection<Data>();

db.Add(new Data { Name = "person1", Description = "sssssss", Price = 15 });
db.Add(new Data { Name = "person2", Description = "okokok", Price = 12 });

它将很好地生成列和数据..但是如果我用 XAML 编写它就不能显示任何东西

<DataGrid ItemsSource="{Binding db}" AutoGenerateColumns="True"/>

我找不到将此集合绑定(bind)到 DataGrid 的方法。请告诉我为什么

这是我所有的xaml

<Window x:Class="testt.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<StackPanel Orientation="Vertical" Name="Panel">
<TextBlock Name="count"/>
<DataGrid ItemsSource="{Binding db}" AutoGenerateColumns="True"/>
</StackPanel>
</Grid>
</Window>

谢谢

最佳答案

如果您不使用 MVVM,请在您的代码中尝试此操作,

DataGrid dg = new DataGrid();
dg.AutoGenerateColumns = true;
dg.ItemsSource = db;
this.DataContext = this; //or put this line in constructor.

数据库在哪里

public ObservableCollection<Data> db = new ObservableCollection<Data>();

db.Add(new Data { Name = "person1", Description = "sssssss", Price = 15 });
db.Add(new Data { Name = "person2", Description = "okokok", Price = 12 });

在 Xaml 中,

<Window x:Class="testt.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<StackPanel Orientation="Vertical" Name="Panel">
<TextBlock Name="count"/>
<DataGrid ItemsSource="{Binding db}" AutoGenerateColumns="True"/>
</StackPanel>
</Grid>
</Window>

关于c# - 无法将 ObservableCollection 绑定(bind)到 DataGrid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19926883/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com