WPF Datagrid:不显示任何数据

时间:2010-11-19 09:05:43

标签: c# wpf vb.net datagrid

有人可以告诉我为什么我的WPF DataGrid中没有显示数据,代码如下:

<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; }
}

2 个答案:

答案 0 :(得分:1)

好。这里有很多问题。

  1. 您将DataContext设置为new Customers()对象而不是客户集合(即list
  2. 为了将ItemsSource直接绑定到将成为集合的DataContext,应该有ItemsSource="{Binding}"
  3. 据我所知,DataGrid默认情况下AutoGenerateColumnstrue,因此它会有4列,2由您自己创建,2自动生成。

答案 1 :(得分:0)

除了alpha-mouse所说的一切,这都是钱......

考虑使您的数据上下文成为ObservableCollection类型的类成员:

public partial class Window1 : Window
{
  private ObservableCollection<Customers> customers;

  public Window1()
  {
      InitializeComponent();

      this.customers = new ObservableCollection<Customers>();

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