C# WPF Datagrid:未显示任何数据

C# WPF Datagrid:未显示任何数据,c#,wpf,vb.net,datagrid,C#,Wpf,Vb.net,Datagrid,有人能告诉我为什么我的WPF数据网格中没有显示具有以下代码的数据: <Window x:Class="WpfApplication1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="30

有人能告诉我为什么我的WPF数据网格中没有显示具有以下代码的数据:

<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300"
    xmlns:my="http://schemas.microsoft.com/wpf/2008/toolkit"
        >
    <Grid>
        <my:DataGrid Name="myDataGrid" ItemsSource="{Binding Customers}">
            <my:DataGrid.Columns>
                <my:DataGridTextColumn Header="Name" Binding="{Binding Name}" />
                <my:DataGridTextColumn Header="Name1" Binding="{Binding Name1}" />
            </my:DataGrid.Columns>
        </my:DataGrid>
    </Grid>
</Window>

public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();

        IList<Customers> list = new List<Customers>();
        list.Add(new Customers() { Name = "Name1", Name2 = "Name2" });
        list.Add(new Customers() { Name = "Name1", Name2 = "Name2" });
        list.Add(new Customers() { Name = "Name1", Name2 = "Name2" });

        myDataGrid.DataContext = new Customers() { Name = "Name1", Name2 = "Name2" };
    }
}

public class Customers
{
    public string Name { get; set; }
    public string Name2 { get; set; }
}

公共部分类Window1:Window
{
公共窗口1()
{
初始化组件();
IList list=新列表();
添加(新客户(){Name=“Name1”,Name2=“Name2”});
添加(新客户(){Name=“Name1”,Name2=“Name2”});
添加(新客户(){Name=“Name1”,Name2=“Name2”});
myDataGrid.DataContext=新客户(){Name=“Name1”,Name2=“Name2”};
}
}
公共类客户
{
公共字符串名称{get;set;}
公共字符串名称2{get;set;}
}

很好。这里有很多问题

  • 您正在将
    DataContext
    设置为
    newcustomers()
    对象,而不是客户集合(即
    列表
  • 应该有
    ItemsSource=“{Binding}”
    ,以便将ItemsSource直接绑定到将成为集合的DataContext
  • 据我所知,
    DataGrid
    默认情况下是
    AutoGenerateColumns
    true
    ,因此它将有4列,2列由您自己创建,2列由自动生成

  • 除了阿尔法老鼠说的一切,都是钱的问题

    考虑将数据上下文设置为ObservableCollection类型的类成员:

    public partial class Window1 : Window
    {
      private ObservableCollection<Customers> customers;
    
      public Window1()
      {
          InitializeComponent();
    
          this.customers = new ObservableCollection<Customers>();
    
    公共部分类窗口1:窗口
    {
    私人可观测收集客户;
    公共窗口1()
    {
    初始化组件();
    this.customers=新的ObservableCollection();
    

    使用ObservableCollection而不是List可确保网格将自动获取对集合内容的更改,而无需执行任何类型的NotifyPropertyChanged。

    Ups,在我的代码中,我确实将DataContext设置为我的List。您在上面提出的第2点修复了问题,感谢您确实应该设置DataCon将视图的文本转换为ViewModel类,并使您的客户集合成为ViewModel的属性。