I'm trying to implement the "1st Approach" as documented at: Filling a Datagrid with dynamic Columns
I've modified the code to include 2 rows and added a User class. I've run into two problems: 1) the "fixed" columns don't display the data, and 2) if I try to edit the data in the DataGrid, the program aborts (under debug it indicates that I can't edit the data).
How do I get the "fixed" columns to display data and how do I make the columns editable?
public MainWindow()
{
InitializeComponent();
var newColumnNames = new string[] { "Name1", "Name2" };
//var users = new User[] { new User { Id = "First User" } };
var users = new User[] { new User { Id = "First User", Image = "image 1" } ,
new User { Id = "Second User", Image="image 2"}};
var newProps = new Dictionary<string, object>[]
{
new Dictionary<string, object>
{
{ "Name1", "First Name of First User" },
{ "Name2", "Second Name of First User" },
},
new Dictionary<string, object>
{
{"Name1", "First Name of Second User" },
{"Name2", "Second Name of Second User" }
}
};
//Column Headers
AddColumns(newColumnNames);
PopulateRows(users, newProps);
}
void AddColumns(string[] newColumnNames)
{
foreach(string name in newColumnNames)
{
grid.Columns.Add(new DataGridTextColumn
{
// bind to a dictionary property
Binding = new Binding("Custom[" + name + "]"),
Header = name,
IsReadOnly = false
});
}
}
void PopulateRows(User[] users, Dictionary<string, object>[] customProps)
{
var customUsers = users.Select((user, index) => new CustomUser
{
Custom = customProps[index]
});
grid.ItemsSource = customUsers;
}
}
XAML File
<DataGrid x:Name="grid" HorizontalAlignment="Left" Height="409" VerticalAlignment="Top" Width="782" AutoGenerateColumns="False" CanUserAddRows="True" >
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Id}" Header="id" IsReadOnly="False"/>
<DataGridTextColumn Binding="{Binding Image}" Header="image" IsReadOnly="False"/>
</DataGrid.Columns>
</DataGrid>
Supporting code includes:
class CustomUser : User
{
public Dictionary<string, object> Custom { get; set; }
public CustomUser() : base()
{
Custom = new Dictionary<string, object>();
}
}