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

标签 c# wpf xaml datagrid itemssource

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

相关文章:

xaml - wp 8 xaml/C# 应用程序上的 xaml 按钮中有 2 行文本

c# - 在 VBA 中使用从 C# 构建的 .xll/.dll

C#类型转换,如何避免报错?

c# - Request.CreateResponse 与response.Content?

c# - 如何在 WPF 中将值从一个用户控件传递到另一个用户控件。

c# - 如何移动 WPF 应用程序的 I18n 文件夹

c# - 禁用时更改按钮颜色

c# - 在 C# 中使函数非阻塞/异步的简单方法?

c# - 在代码隐藏中修改列表框的数据模板属性

c# - 使用 XAML 属性在 RichTextBox 中插入图像