开发者

WPF Datagrid: No data being displays

开发者 https://www.devze.com 2023-01-26 02:12 出处:网络
Can someone please tell me why no data is being displaysed in my WPF DataGrid with the following code:

Can someone please tell me why no data is being displaysed in my WPF DataGrid with the following code:

<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="ht开发者_如何学JAVAtp://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; }
}


Well. There are a number of issues here.

  1. You are setting DataContext to be new Customers() object instead of a collection of customers (namely the list)
  2. There should be ItemsSource="{Binding}" in order to bind ItemsSource directly to the DataContext which is going to be the collection.
  3. As far as I remember DataGrid has it's AutoGenerateColumns being true by default, so it will have 4 columns, 2 created by yourself and 2 autogenerated.


In addition to everything alpha-mouse said, which was all on the money...

consider making your data context a class member of type ObservableCollection:

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

  public Window1()
  {
      InitializeComponent();

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

Using an ObservableCollection instead of List ensures that changes to the collection content will automatically be picked up by the grid without you having to do any kind of NotifyPropertyChanged.

0

精彩评论

暂无评论...
验证码 换一张
取 消