I have a WPF DataGrid
written in XAML that I'm converting to C# (don't ask).
It looks something like this (some properties omitted for brevity):
var Card = new DataGrid() {
Background = Brushes.LightYellow,
BorderBrush = Brushes.DimGray,
ColumnWidth = new DataGridLength(100),
Columns = {
new DataGridTextColumn() {
Binding = new Binding("In"),
Header = "In"
},
new DataGridTextColumn() {
Binding = new Binding("Out"),
Header = "Out"
},
new DataGridTextColumn() {
Binding = new Binding("Hours"),
Header = "Hours"
}
},
RowHeaderTemplate = new DataTemplate(typeof(DataGridRowHeader)) {
VisualTree = Days
},
RowHeaderWidth = 115,
RowHeight = 50
};
Days
is setup like so:
var Days = new FrameworkElementFactory(typeof(TextBlock));
Days.SetBinding(TextBlock.TextProperty, new Binding("Day"));
Days.SetValue(TextBlock.BackgroundProperty, Brushes.Lime);
When run, the DataGrid
's RowHeader
is blank (and LightYellow
, not Lime
).
I've tried Card.RowHeaderTemplate.VisualTree = Days;
also, to no avail.
Where am I going wrong? How can I set the RowHeaderTemplate
programmatically?
Templates should be created using loading from XAML. Using element factories is obsolete and no longer supported (it may work in some cases, but won't work in other).
For example, Caliburn.Micro creates default data templates like this:
Another link you may find useful: Creating WPF Data Templates in Code The Right Way. It includes a sample of creating XAML string using XML and XAML classes, with references to assemblies and stuff.