Search code examples
c#treeviewwinui-3winui

Is a Frame the best Way to Host a Page within a Grid Layout Cell


Please excuse if this is a very basic question, but I'm coming from a WinForms background.

I'm looking to include a tree view on the left of the application window for a WinUI 3 project, which will determine the content of a data grid on the right-hand side. The tree view is a simple, static element, which I don't want to be a split view. Hosting the tree view in a cell of a grid layout would work perfectly. That said, I'd like the tree view to have its own XAML page and ViewModel and have been looking into ways of hosting the tree view page into the grid. It appears Frame is a good candidate, but the Windows documentation states "You use the Frame control to support navigation to Page instances." in this help page: https://learn.microsoft.com/en-us/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.frame?view=windows-app-sdk-1.5

Is there a simpler or better option than a Frame, or does a Frame work fine even though I'm there is no navigation or switching to other pages?


Solution

  • You can create Page, which is a UserControl, or you can create UserControl:

    TreeViewUserControl.xaml

    <UserControl
        x:Class="WinUIApp3.TreeViewUserControl"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:local="using:WinUIApp3"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d">
    
        <Grid>
            <TreeView>
                <TreeView.RootNodes>
                    <TreeViewNode Content="A" />
                    <TreeViewNode Content="B" />
                    <TreeViewNode Content="C" />
                </TreeView.RootNodes>
            </TreeView>
        </Grid>
    </UserControl>
    

    TreeViewUserControl.xaml.cs

    public sealed partial class TreeViewUserControl : UserControl
    {
        public TreeViewUserControl()
        {
            this.InitializeComponent();
        }
    
        public TreeViewModel ViewModel { get; } = new();
    }