0

有人可以告诉我为什么我的 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; }
}
4

2 回答 2

1

好。这里有很多问题。

  1. 您设置DataContextnew Customers()对象而不是客户集合(即list
  2. ItemsSource="{Binding}"为了将 ItemsSource 直接绑定到将成为集合的 DataContext 应该有。
  3. 据我记得DataGridAutoGenerateColumnstrue默认的,所以它将有 4 列,2 列由您自己创建,2 列自动生成。
于 2010-11-19T09:14:41.117 回答
0

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

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

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

  public Window1()
  {
      InitializeComponent();

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

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

于 2010-11-19T09:48:14.247 回答