Search code examples
c#xamluwp

Build XAML Elements in Runtime, From a List of Data in UWP C#?


I have a List<string> which is below,

List<string> animeList = new()
{
    "Current",
    "Planning",
    "Paused",
    "Dropped",
    "Custom List"
}

I want to build a XAML Element in Runtime from the data available in the above list. To be precise, I want to build a NavigationViewItem which is from Microsoft.UI.Xaml.Controls Like the below Image,

enter image description here

The Xaml in this picture is hardcoded and that XAML is Below,

<winui:NavigationViewItem Content="Anime List" x:Name="animeList">
                <winui:NavigationViewItem.Icon>
                    <FontIcon Glyph="&#xE29B;"
                              Style="{StaticResource FontIconStyle}"/>
                </winui:NavigationViewItem.Icon>
                <winui:NavigationViewItem.MenuItems>
                    <winui:NavigationViewItem Content="Current"/>
                    <winui:NavigationViewItem Content="Planning"/>
                    <winui:NavigationViewItem Content="Paused"/>
                    <winui:NavigationViewItem Content="Dropped"/>
                    <winui:NavigationViewItem Content="Custom List"/>
                </winui:NavigationViewItem.MenuItems>
            </winui:NavigationViewItem>

Here the winui xml namespace is below,

xmlns:winui="using:Microsoft.UI.Xaml.Controls"

Here, instead of hardcoding the NavigationViewItem, I want to build the NavigationViewItem from the above animeList in the Runtime. How can I do it.

Thanks in Advance...


Solution

  • Bind the NavigationViewItem to your list of items using the MenuItemsSource property:

    <NavigationViewItem Content="Anime List"
                        MenuItemsSource="{x:Bind animeList}">
        <NavigationViewItem.Icon>
            <FontIcon Glyph="&#xE29B;" Style="{StaticResource FontIconStyle}"/> />
        </NavigationViewItem.Icon>
    </NavigationViewItem>
    

    There is no reason to loop explicitly.