如果我用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/