WinUI 3 C++ Controls Guide – Dynamically Add Items to ListBox

Now we will implement a frequently used function: dynamically add items to a ListBox. Click the button to insert a new item into the ListBox’s Items collection. This feature is widely adopted in most software programs.

First add a ListBox and a Button in XAML

<Border Padding="14" BorderThickness="1" BorderBrush="Gray" CornerRadius="8">
    <StackPanel Spacing="12">
        <TextBlock Text="5. ListBox - Fixed Height Single/Multi Select List" FontWeight="SemiBold" FontSize="14" Margin="0,0,0,8"/>
        <Button Content="Add Item" Click="Button_Click"/>
        <ListBox Width="280" Height="140" x:Name="myListBox" SelectionMode="Multiple">
            <ListBoxItem Content="Documents"/>
            <ListBoxItem Content="Pictures"/>
            <ListBoxItem Content="Videos"/>
            <ListBoxItem Content="Audios"/>
            <ListBoxItem Content="Installers"/>
        </ListBox>
    </StackPanel>
</Border>Code language: C++ (cpp)

We added a button; clicking it will generate a new ListBox item. To operate the ListBox in backend code, we assign it a name: x:Name=”myListBox”

Press F12 to generate the event handler function automatically.

void winrt::App6::implementation::MainWindow::Button_Click(
winrt::Windows::Foundation::IInspectable const& sender,
 winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e)
{
    // Get the Items collection of ListBox
    auto itemCollection = myListBox().Items();

    itemCollection.Append(box_value(L"New Item"));
}Code language: C++ (cpp)

In the event function, we first obtain the control instance named x:Name=”myListBox”, get its Items collection, then use Append to add new content.

WinUI 3 C++ Controls Guide – Dynamically Add Items to ListBox

Leave a Reply

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