Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 779683
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T19:57:52+00:00 2026-05-14T19:57:52+00:00

I am trying to add controls to a UserControl dynamically (programatically). I get a

  • 0

I am trying to add controls to a UserControl dynamically (programatically). I get a generic List of objects from my Business Layer (retrieved from the database), and for each object, I want to add a Label, and a TextBox to the WPF UserControl and set the Position and widths to make look nice, and hopefully take advantage of the WPF Validation capabilities. This is something that would be easy in Windows Forms programming but I’m new to WPF. How do I do this (see comments for questions) Say this is my object:

public class Field {
   public string Name { get; set; }
   public int Length { get; set; }
   public bool Required { get; set; }
}

Then in my WPF UserControl, I’m trying to create a Label and TextBox for each object:

public void createControls() {
    List<Field> fields = businessObj.getFields();

    Label label = null;
    TextBox textbox = null;

    foreach (Field field in fields) {
        label = new Label();
        // HOW TO set text, x and y (margin), width, validation based upon object? 
        // i have tried this without luck:
        // Binding b = new Binding("Name");
        // BindingOperations.SetBinding(label, Label.ContentProperty, b);
        MyGrid.Children.Add(label);

        textbox = new TextBox();
        // ???
        MyGrid.Children.Add(textbox);
    }
    // databind?
    this.DataContext = fields;
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-14T19:57:53+00:00Added an answer on May 14, 2026 at 7:57 pm

    Alright, second time’s the charm. Based on your layout screenshot, I can infer right away that what you need is a WrapPanel, a layout panel that allows items to fill up until it reaches an edge, at which point the remaining items flow onto the next line. But you still want to use an ItemsControl so you can get all the benefits of data-binding and dynamic generation. So for this we’re going to use the ItemsControl.ItemsPanel property, which allows us to specify the panel the items will be put into. Let’s start with the code-behind again:

    public partial class Window1 : Window
    {
        public ObservableCollection<Field> Fields { get; set; }
    
        public Window1()
        {
            InitializeComponent();
    
            Fields = new ObservableCollection<Field>();
            Fields.Add(new Field() { Name = "Username", Length = 100, Required = true });
            Fields.Add(new Field() { Name = "Password", Length = 80, Required = true });
            Fields.Add(new Field() { Name = "City", Length = 100, Required = false });
            Fields.Add(new Field() { Name = "State", Length = 40, Required = false });
            Fields.Add(new Field() { Name = "Zipcode", Length = 60, Required = false });
    
            FieldsListBox.ItemsSource = Fields;
        }
    }
    
    public class Field
    {
        public string Name { get; set; }
        public int Length { get; set; }
        public bool Required { get; set; }
    }
    

    Not much has changed here, but I’ve edited the sample fields to better match your example. Now let’s look at where the magic happens- the XAML for the Window:

    <Window x:Class="DataBoundFields.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:DataBoundFields"
    Title="Window1" Height="200" Width="300">
    <Window.Resources>
        <local:BoolToVisibilityConverter x:Key="BoolToVisConverter"/>
    </Window.Resources>
    <Grid>
        <ListBox x:Name="FieldsListBox">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <Label Content="{Binding Name}" VerticalAlignment="Center"/>
                        <TextBox Width="{Binding Length}" Margin="5,0,0,0"/>
                        <Label Content="*" Visibility="{Binding Required, Converter={StaticResource BoolToVisConverter}}"/>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
            <ListBox.ItemsPanel>
                <ItemsPanelTemplate>
                    <WrapPanel Orientation="Horizontal" 
                               Height="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=ActualHeight}"
                               Width="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=ActualWidth}"/>
                </ItemsPanelTemplate>
            </ListBox.ItemsPanel>
        </ListBox>
    </Grid>
    

    First, you will notice that the ItemTemplate has changed slightly. The label is still bound to the name property, but now the textbox width is bound to the length property (so you can have textboxes of varying length). Furthermore, I’ve added a “*” to any fields that are required, using a simplistic BoolToVisibilityConverter (which you can find the code for anywhere, and I will not post here).

    The main thing to notice is the use of a WrapPanel in the ItemsPanel property of our ListBox. This tells the ListBox that any items it generates need to be pushed into a horizontal wrapped layout (this matches your screenshot). What makes this work even better is the height and width binding on the panel- what this says is, “make this panel the same size as my parent window.” That means that when I resize the Window, the WrapPanel adjusts its size accordingly, resulting in a better layout for the items.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to figure out if there is a way to dynamically add controls
I am trying to add an instance of UserControl each time on button_click event,
I'm trying to add an overlay effect to my UserControl and I know that's
I have downloaded the ComponentOne Silverlight controls, and am trying to add the HTMLHost
So I'm trying to dynamically load a usercontrol into a placeholder in another usercontrol
Trying to find the best way to dynamically add a direction attribute to each
I'm trying to add some user controls on a page. Thats easy, I just
I'm trying to build an usercontrol wich is able to take elements from XAML
I am trying to create a Word add-in (Word 2007, VS 2008) to get
Trying to dynamically add a user control that dynamically generates content. The User Control

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.