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

Time:05-24

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...

CodePudding user response:

You can create a loop, and for every item, you create a new NavigationViewItem

public MainPage()
{
    this.InitializeComponent();

    foreach (string anime in animeList)
    {
        animeNavigationViewItem.MenuItems.Add(
            new winui.NavigationViewItem
            {
                 Content = anime
            });
    }
}

CodePudding user response:

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.

  • Related