TextBox AddTextBoxes(ItemsControl control, IEnumerable <EditableTreeViewLevelRule> rules) { EditableTreeViewLevelRule thisLayerRules = rules.First(); TextBox tb = new TextBox() { MinWidth = 50, Text = thisLayerRules.HelpText }; tb.GotKeyboardFocus += (o, e) => { if (tb.Text == thisLayerRules.HelpText) { tb.Text = ""; } }; tb.LostKeyboardFocus += (o, e) => { if (String.IsNullOrWhiteSpace(tb.Text)) { tb.Text = thisLayerRules.HelpText; } }; tb.KeyUp += (o, e) => { tb.Background = new SolidColorBrush(Colors.White); if (e.Key != Key.Enter) { return; } e.Handled = true; // enter button pressed string newItemText = tb.Text; if (thisLayerRules.Unique) { if (control.ContainsChildHeader(newItemText)) { tb.Background = new SolidColorBrush(Colors.Red); return; } } TreeViewItem tvi = new TreeViewItem() { Header = newItemText }; TextBox innerTb = null; if (rules.Count() > 1) { tvi.IsExpanded = true; innerTb = AddTextBoxes(tvi, rules.Skip(1)); } tb.Text = ""; control.Items.Insert(control.Items.Count - 1, tvi); // TODO: fix this. doesn't work // the keyboard focus should switch to the inner textbox // when a new section is added if (innerTb != null) { Keyboard.Focus(innerTb); } }; if (rules.Count() > 1) { foreach (object item in control.Items) { TreeViewItem tvi = item as TreeViewItem; if (tvi == null) { continue; } AddTextBoxes(tvi, rules.Skip(1)); } } control.Items.Add(tb); return(tb); }