Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,785 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
I've seen some example of creating DataTemplate
with StackPanel
and deprecated FrameworkElementFactory. For the Tenant
under Lease
section I want to have a DataTemplate with a Grid with two columns and two TextBlocks (one for Name and the other for Phone):
The SelectItem
, tenant, is my control and want the following dataTemplate
Grid to be its ItemTemplate
var nameBlock = new TextBlock();
var phoneBlock = new TextBlock();
Grid.SetColumn(phoneBlock, 1);
var dataTemplate= new Grid() {
ColumnDefinitions = {
new ColumnDefinition(),
new ColumnDefinition(){Width = GridLength.Auto}
},
Children = {nameBlock, phoneBlock}
};
tenant = new SelectItem() {
Hint = "Tenant",
IsRequired = true,
Icon = Icons.Tenant,
SelectedValuePath = nameof(Tenant.Id),
SearchPath = nameof(Tenant.Name),
DisplayPath = nameof(Tenant.Name),
ItemTemplate = dataTemplate
};
this way it doesn't work!
The deprecated method still works:
var gridFactory = new FrameworkElementFactory(typeof(Grid));
var column1Factory = new FrameworkElementFactory(typeof(ColumnDefinition));
var column2Factory = new FrameworkElementFactory(typeof(ColumnDefinition));
var nameFactory = new FrameworkElementFactory(typeof(TextBlock));
var phoneFactory = new FrameworkElementFactory(typeof(TextBlock));
column1Factory.SetValue(ColumnDefinition.WidthProperty, new GridLength(1, GridUnitType.Star));
column2Factory.SetValue(ColumnDefinition.WidthProperty, new GridLength(1, GridUnitType.Auto));
phoneFactory.SetValue(Grid.ColumnProperty, 1);
nameFactory.SetBinding(TextBlock.TextProperty, new Binding("Name"));
phoneFactory.SetBinding(TextBlock.TextProperty, new Binding("ContactNo"));
gridFactory.AppendChild(column1Factory);
gridFactory.AppendChild(column2Factory);
gridFactory.AppendChild(nameFactory);
gridFactory.AppendChild(phoneFactory);
tenant = new SelectItem() {
Hint = "Tenant",
IsRequired = true,
Icon = Icons.Tenant,
SelectedValuePath = nameof(Tenant.Id),
SearchPath = nameof(Tenant.Name),
//DisplayPath = nameof(Tenant.Name)
ItemTemplate = new DataTemplate() { VisualTree = gridFactory }
};
BUT boring! It'd be nice if I could do like this:
var nameBlock = new TextBlock();
var phoneBlock = new TextBlock();
Grid.SetColumn(phoneBlock, 1);
var template = new DataTemplate(){ new Grid() {
ColumnDefinitions = {
new ColumnDefinition(),
new ColumnDefinition(){Width = GridLength.Auto}
},
Children = { nameBlock, phoneBlock }
};