Reputation: 4376
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="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; }
}
Upvotes: 0
Views: 2607
Reputation: 2093
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.
Upvotes: 0
Reputation: 5003
Well. There are a number of issues here.
DataContext
to be new Customers()
object instead of a collection of customers (namely the list
)ItemsSource="{Binding}"
in order to bind ItemsSource directly to the DataContext which is going to be the collection.DataGrid
has it's AutoGenerateColumns
being true
by default, so it will have 4 columns, 2 created by yourself and 2 autogenerated.Upvotes: 1