Search code examples
c#wpfxamluser-interfaceprogrammatically-created

Creating multiple UI Elements dynamically during runtime - C# WPF


I'm fairly new to C# and WPF, but I started building an application which should have a function of listing Items with a few details. Currently it looks like

The data for these 'items' (one item is multiple labels enclosed in a border (at a later time I would like to add a picture as well)) is loaded in through a REST Service and I don't know how many items will be responded. Now I have the problem of not beeing able to create the labels statically within the xaml because of the variating number of items recieved.

My question here is, how can I create multiple labels (as well as a border and an image) programmatically, align them correctly in the window and address the labels to fill them with data?

Thanks a lot for your help!


Solution

  • As you indicated in your comment, a ListBox will probably suit your purposes. The general idea is that you want to specify the format of the ListBox via an ItemTemplate, and in the ItemTemplate specify a DataTemplate with the necessary controls to support your API data, with bindings specified to a model mapped from the JSON. An incomplete example of the XAML:

    <ListBox x:Name="transactionsListBox">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Border BorderBrush="Black" BorderThickness=".5" Padding="1">
                    <StackPanel>
                        <Label x:Name="id" Content="{Binding Path=Id}" />
                        <Label x:Name="item_id" Content="{Binding Path=Item_Id}" />
                        <Label x:Name="price" Content="{Binding Path=Price}" />
                        <Label x:Name="quantity" Content="{Binding Path=Quantity}" />
                        <Label x:Name="created" Content="{Binding Path=Created}" />
                        <Label x:Name="purchased" Content="{Binding Path=Purchased}" />
                    </StackPanel>
                </Border>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
    

    The Path= property of the bindings above need to match the property names of the model you create to store the transactions from your REST call. Then, when you have an instance of a list of that model type, your code would want to do something like:

    List<Transaction> myTransactions = apiCall.response.mapToMyModel() // pseduocode
    transactionsListBox.DataContext = myTransactions;