Reputation: 101
I am trying to set a DataGrid's ItemSource equal to a list, and then display the content of that list.
My XAML looks like
<Window x:Class="DataGridDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:DataGridDemo"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<DataGrid x:Name="aGrid" ItemsSource= "{Binding actorList}" />
</Grid>
</Window>
My MainWindow code looks like
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using A1;
namespace DataGridDemo
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
List<Actor> actorList = new List<Actor>();
public MainWindow()
{
Actor a = new Actor("Jaba",32);
Actor b = new Actor("Java", 46);
Actor c = new Actor("Jaga", 23);
actorList.Add(a);
actorList.Add(b);
actorList.Add(c);
InitializeComponent();
aGrid.ItemsSource = actorList;
}
}
}
and if it matter my actor class looks like
namespace A1
{
public class Actor
{
Random rand { get; set; }
String name { get; set; }
int age { get; set; }
public Actor()
{
name = "Blank Blankerson";
age = rand.Next(80) + 6;
}
public Actor(String n)
{
name = n;
age = rand.Next(80) + 6;
}
public Actor(String n, int a)
{
age = a;
name = n;
}
public override String ToString()
{
return name + "," + age.ToString();
}
}
Every time the code runs, it generates 3 blank rows like so
Every tutorial on the internet I can find says you just set dataGrid.ItemSource = List. This has only generated the following error in both my attempts. It's frustrating because I am following the tutorials and this is still my result.
So, how do I make a WPF DataGrid display a List?
Upvotes: 1
Views: 71
Reputation: 101
DataGrid requires that the get and set methods be public. I changed this accordingly. It now displays.
Upvotes: 1
Reputation: 222542
You need to set AutoGenerateColumns="True"
unless if you are defining your own template for the columns
<DataGrid x:Name="aGrid" AutoGenerateColumns="True" ItemsSource= "{Binding actorList}" />
EDIT
You should set the datacontext for the window
InitializeComponent();
DataContext = this;
aGrid.ItemsSource = actorList;
actorList needs to be a property in your datacontext, i.e. the mainwindow
Additionally you should think about implementing INotifyPropertyChanged in your model
Upvotes: 0