How to Add a Control to System.Windows.Controls.MenuItem Programmatically in WPF

I’m working on a new feature for Jenkins Toolset. It’s the feature that allows you to invoke a job with parameters. I need to add parameters to MenuItem according to parameter types. I have not completed the feature yet but I figured out a way to add controls programmatically, so here is the sample code.

var g = new System.Windows.Controls.Grid();
g.ColumnDefinitions.Add(new System.Windows.Controls.ColumnDefinition());
g.ColumnDefinitions.Add(new System.Windows.Controls.ColumnDefinition());

var lblText = new System.Windows.Controls.TextBlock();
g.Children.Add(lblText);
lblText.Text = $"{p.Name} ";
System.Windows.Controls.Grid.SetColumn(lblText, 0);

var txtBox = new System.Windows.Controls.TextBox();
txtBox.Width = 100;
g.Children.Add(txtBox);
System.Windows.Controls.Grid.SetColumn(txtBox, 1);

parItem.Header = g;

Here is the sample UI.

It took me a while to figure this out, so I thought I’d share it here in my blog. 🙂

Author: admin

A software engineer in greater Seattle area

Leave a Reply

Your email address will not be published. Required fields are marked *