ArchieTiger
ArchieTiger

Reputation: 2243

Dynamic control in WPF

I am trying to create dynamic controls (Label and combobox) in a WPF form, and have them arranged accordingly. What's the best practice in doing this and also how do I make the window resize to fit the controls as they grow ?

public MainWindow()
    {
        MyEntities db = new MyEntities();
        InitializeComponent();
        var ID = db.Courses.Where(f => f.CourseId!=null).ToList();
        foreach (var c in ID) 
        {
            ComboBox c = new ComboBox();                
            this.stackpanel.Children.Add(c);
        }
    }            

XAML

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">

    <StackPanel Name= "stackpanel"/>     
</Window>

Upvotes: 1

Views: 1323

Answers (1)

Rafal
Rafal

Reputation: 12619

You can declare ItemsControl and provide item template:

 <ItemsControl ItemsSource="{Binding Collection}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding Name}" />
                 <ComboBox ... />
                </StackPanel>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>

As Batuu suggested you can use other controls like ListView to get additional behavor.

For window growing with your controls list you can use Window.SizeToContent property as was suggested by LPL in comment.

<Window x:Class="WpfApplication2.MainWindow"
    ...
    SizeToContent="Height">

Available options are described here.

Upvotes: 3

Related Questions