WPF Datagrid: No data being displays
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.
- You are setting
DataContextto benew Customers()object instead of a collection of customers (namely thelist) - There should be
ItemsSource="{Binding}"in order to bind ItemsSource directly to the DataContext which is going to be the collection. - As far as I remember
DataGridhas it'sAutoGenerateColumnsbeingtrueby 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.
加载中,请稍侯......
精彩评论