I've to pivot information data from a query, and show images based on value read from the underlying database.
Let's say I have this data out of my query:
Identifiant|ProcessId|AlarmLevel
BOUDA25 | 100 | 1
BOUDA25 | 110 | 1
BOUDA25 | 130 | 1
BOUDA25 | 205 | 2
BOUDA25 | 210 | 2
I now want to make the following WPF DataGrid display the actual images represented by images/circle_orange.ico
, etc.
So far my code resembles this:
private void PopulateGrid(IEnumerable<AlarmeViewModel> alarmes) {
// Used to pivot the information data
var table=new DataTable();
// Generates the columns based on rows
table.Columns.Add("Identifiant");
table.Columns.Add("=>");
alarmes.ForEach(a => a.Processes.ForEach(pid => table.Columns.Add(columnName:pid, type typeof(string))));
// Generates the rows
var images = new string[] {
"images/circle_grey.ico",
"images/circle_orange.ico",
"images/circle_yellow.ico",
"images/circle_red.ico",
"images/circle_green.ico"
};
alarmes.ForEach(a => {
var row = table.NewRow();
row[0] = a.Identifiant
for(int i=0; i<a.Niveaux.Count; row[a.Processes[i]]=images[a.AlarmLevel[1]], i++);
table.Rows.Add(row);
});
// Refreshes the DataGrid content
alarmDataGrid.BeginInit();
alarm.DataGrid.ItemsSource=table.DefaultView;
alarmDataGrid.EndInit();
}
Now I'm stuck since three days to make those image display through an ImageSource binding.
I tried to let the DataGrid autogenerate the columns by itself, and I also tried by adding them in the code behind from the accepted answer of this question:
And this one also:
And I just can't get it. I know I'm close, but still missing the obvious, I guess.
You could handle the AutoGeneratingColumn
event and programmatically create a DataGridTemplateColumn
that contains an Image
element. Try this:
private void OnAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
if (e.PropertyName != "Identifiant" && e.PropertyName != "=>")
{
FrameworkElementFactory image = new FrameworkElementFactory(typeof(Image));
image.SetBinding(Image.SourceProperty, new Binding(e.PropertyName));
e.Column = new DataGridTemplateColumn
{
CellTemplate = new DataTemplate() { VisualTree = image },
Header = e.PropertyName
};
}
}