Search code examples
c#windowsxamldesktop-applicationwinui-3

How to customize the content of a NavigationViewItem in WinUI 3.0?


I am trying to customize the Content of a NavigationViewItem in WinUI 3.0
Why isn't the button in the NavigationViewItem visible?
It works fine when I remove data binding though

XAML:

<?xml version="1.0" encoding="utf-8"?>
<Window
    x:Class="Test.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Test"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <NavigationView x:Name="TestNavigationView" PaneDisplayMode="LeftMinimal" IsSettingsVisible="False" IsBackButtonVisible="Collapsed" DataContext="{Binding}">
        <NavigationView.MenuItems>
            <NavigationViewItem>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Name}" VerticalAlignment="Center" />
                    <Button Margin="8, 0, 0, 0" Content="Btn" />
                </StackPanel>
            </NavigationViewItem>
        </NavigationView.MenuItems>
    </NavigationView>
</Window>

CS:

namespace Test
{
    public class Item
    {
        public string Name { get; set; }
    }

    public sealed partial class MainWindow : Window
    {
        ObservableCollection<Item> items = new ObservableCollection<Item>();
        public MainWindow()
        {
            this.InitializeComponent();

            TestNavigationView.MenuItemsSource = items;

            items.Add(new Item { Name = "Test1" });
            items.Add(new Item { Name = "Test2" });
        }
    }
}

Solution

  • Your buttons are hidden because PaneDisplayMode is set to LeftMinimal. You should be able to see your buttons if you click the menu button, the button with 3 horizontal lines, or just set PlaneDisplayMode to the other options.

    LeftMinimal:
    Only the menu button is shown until the pane is opened. When opened, the pane overlays the left side of the content.

    UPDATE:

    To render the items you are setting in code-behind, you need to specify how you want to render them using an item template:

    <NavigationView
        x:Name="TestNavigationView"
        IsBackButtonVisible="Collapsed"
        IsSettingsVisible="False"
        PaneDisplayMode="LeftMinimal">
        <NavigationView.MenuItemTemplate>
            <DataTemplate x:DataType="local:Item">
                <StackPanel Orientation="Horizontal">
                    <TextBlock
                        VerticalAlignment="Center"
                        Text="{x:Bind Name}" />
                    <Button
                        Margin="8,0,0,0"
                        Content="Btn" />
                </StackPanel>
            </DataTemplate>
        </NavigationView.MenuItemTemplate>
    </NavigationView>