简体   繁体   中英

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>

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM