Toolroom Tech Blog

Devlopers Digest

Properly adding UIElements from code

Although it's not the way how you should design your WPF applications, you may try to add UIElements at runtime from code behind. Therefore you should introduce the recently added elements into the XAML namescope. Otherwise you will not be able to find the added item  again and you may run in troubles with animation storyboards, since they use runtime name lookups with their key property "TargetName".

In the sample below, a row with a label and a textbox is added to a grid at runtime:

private void AddParam(int rowId, string labelText, string displayValue)
	grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });

	var label = new Label { Content = labelText };
	label.SetValue(Grid.RowProperty, rowId);
	label.SetValue(Grid.ColumnProperty, 0);

	var textboxName = string.Format("dauerPosParam{0}__O", rowId);
	var textbox = new TextBox { Text = displayValue, Name = textboxName };
	textbox.SetValue(Grid.RowProperty, rowId);
	textbox.SetValue(Grid.ColumnProperty, 1);
	if(FindName(textboxName) == null)
		RegisterName(textboxName, textbox);

Get further Information at FrameworkElement.RegisterName or NameScope.RegisterName.