Skip to content

SidebarView is a WinUI navigation sidebar adapted from the Files app. It hosts a virtualized, flat list of SidebarItem rows, supports tree and grouped expansion, three display modes, a resizable pane, drag and drop (including reordering), flyouts for compact mode, and UI Automation.


Table of Contents ​

  1. Architecture Overview
  2. Types at a Glance
  3. Quick Start
  4. Data Model
  5. SidebarView
  6. SidebarItem
  7. Display Modes
  8. Expansion Behavior
  9. Selection
  10. Drag and Drop
  11. Context Menus
  12. Pane Resizing
  13. Visual States Reference
  14. Template Parts
  15. Theme Resources
  16. Accessibility
  17. Implementation Notes
  18. Troubleshooting

Architecture Overview ​

The sidebar renders a flat list. Hierarchy is expressed through FlatSidebarItem.Depth, not through nested controls. Only compact-mode flyouts render children as nested SidebarItem instances.

Data flow:

  1. The host supplies a flat collection of FlatSidebarItem through MenuItemsSource.
  2. ItemsRepeater realizes a SidebarItem per entry using ItemTemplate.
  3. MenuItemsHost_ElementPrepared assigns Owner and calls HandleItemChange.
  4. SidebarItem subscribes to the model's PropertyChanged and children CollectionChanged, and mirrors presentation data when UseItemPresentation is true.
  5. User interaction raises events on SidebarView.

Types at a Glance ​

TypeKindPurpose
SidebarViewUserControlThe sidebar host: pane, resizer, content area
SidebarItemControlA single row (also used in flyouts and for static footer items)
FlatSidebarItemclassPer-row wrapper carrying depth, opacity, and section-gap state
ISidebarItemModelinterfaceContract for item data
ISidebarItemPresentationModelinterfaceOptional presentation contract (text, tooltip, icon, decorator)
SidebarDisplayModeenumMinimal, Compact, Expanded
SidebarExpanderStyleenumTree, Group
SidebarItemDropPositionenumTop, Bottom, Center
ItemInvokedEventArgsrecordPayload for ItemInvoked
ItemContextInvokedArgsrecordPayload for ItemContextInvoked
ItemDragOverEventArgsrecordPayload for ItemDragOver, supports deferrals
ItemDroppedEventArgsrecordPayload for ItemDropped
SidebarItemAutomationPeerpeerInvoke, ExpandCollapse, SelectionItem
SidebarViewAutomationPeerpeerSelection

Quick Start ​

1. Implement the model ​

csharp
public sealed class NavItem : ISidebarItemModel, ISidebarItemPresentationModel
{
    private bool _isExpanded = true;

    public string? Text { get; init; }
    public object? ToolTip { get; init; }
    public FrameworkElement? IconElement { get; init; }
    public FrameworkElement? ItemDecorator { get; init; }
    public string? Path { get; init; }

    public ObservableCollection<NavItem>? ChildItems { get; init; }
    public object? Children => ChildItems;

    public bool IsExpanded
    {
        get => _isExpanded;
        set
        {
            if (_isExpanded == value)
                return;
            _isExpanded = value;
            PropertyChanged?.Invoke(this, new(nameof(IsExpanded)));
        }
    }

    public event PropertyChangedEventHandler? PropertyChanged;
}

2. Build the flat list ​

csharp
var items = new ObservableCollection<FlatSidebarItem>
{
    new(pinnedHeader, depth: 0),
    new(documents, depth: 0),
    new(downloads, depth: 0),
    new(drivesHeader, depth: 0) { HasExpandedPredecessor = true },
};

Sidebar.MenuItemsSource = items;

3. Declare the control ​

xml
<controls:SidebarView x:Name="Sidebar"
                      DisplayMode="Expanded"
                      OpenPaneLength="260"
                      CanResizePane="True"
                      ExpanderStyle="Tree"
                      ItemInvoked="Sidebar_ItemInvoked"
                      ItemContextInvoked="Sidebar_ItemContextInvoked">
    <Frame x:Name="ContentFrame" />
</controls:SidebarView>

InnerContent is the ContentProperty, so child markup becomes the main content area.

4. Handle events ​

csharp
private void Sidebar_ItemInvoked(object? sender, ItemInvokedEventArgs e)
{
    if (sender is SidebarItem { Item: NavItem item })
        Navigate(item);
}

sender is the SidebarItem that was invoked. SelectedItem has already been updated by the time the event fires.

Built-In Feeding (For Lazy Users) ​

cs
public ObservableCollection<SidebarItemModel> Items { get; } = new()
{
    new SidebarItemModel { Text = "Home", Path = "C:\\Fonts", IconImage = "Home" },
    new SidebarItemModel
    {
        Text = "Folder",
        Children = new()
        {
            new SidebarItemModel { Text = "SubFolder1", Path = "C:\\Folder\\SubFolder1", IconImage = "Folder" },
            new SidebarItemModel { Text = "SubFolder2", Path = "C:\\Folder\\SubFolder2", IconImage = "Folder" }
        }
    },
    new SidebarItemModel { Text = "Drive", Path = "D:\\Drive", IconImage = "CloudDrive" }
};

public SidebarViewMenuSource SidebarViewItems { get; }
public SideBarViewPage()
{
    InitializeComponent();
    SidebarViewItems = new SidebarViewMenuSource(Items);
}

Data Model ​

ISidebarItemModel ​

MemberTypeDescription
Childrenobject?Child collection. A non-null value marks the item as a group header. Implement INotifyCollectionChanged to react to changes.
IsExpandedbool (get/set)Whether children are visible.
Pathstring?Path used for drag and drop.
HasUnrealizedChildrenbool (default false)Renders as expandable even when Children is empty, for lazy loading.
IsLeafWithChildrenbool (default false)Keeps regular row styling and click behavior while still being expandable. Intended for tree-view folders.
CanReorderbool (default false)Allows drag-reorder with top/bottom drop zones.

The interface also extends INotifyPropertyChanged. Raising PropertyChanged with null or an empty string refreshes the entire row.

Properties that the row reacts to by name:

  • Text, ToolTip, IconElement, ItemDecorator
  • IsExpanded
  • HasUnrealizedChildren, IsLeafWithChildren
  • Children

ISidebarItemPresentationModel ​

MemberTypeMaps to
Textstring?SidebarItem.Text and the automation id
ToolTipobject?SidebarItem.ToolTip
IconElementFrameworkElement?SidebarItem.Icon
ItemDecoratorFrameworkElement?SidebarItem.Decorator

Implement this on the model when UseItemPresentation is true. The default item template sets it to true.

FlatSidebarItem ​

MemberDescription
ItemThe wrapped ISidebarItemModel
DepthTree depth, used as NestingLevel
RowOpacityOpacity applied to icon, text, chevron, and decorator. Selection and hover fills stay at full opacity. Useful for dimming hidden items.
HasExpandedPredecessorWhen true, SectionGapMargin becomes 0,12,0,0 to separate sections
SectionGapMarginComputed margin. Changes raise PropertyChanged.

Constructor:

csharp
public FlatSidebarItem(ISidebarItemModel item, int depth, double rowOpacity = 1.0)

Depth and RowOpacity are fixed at construction. Rebuild the wrapper to change them.


SidebarView ​

Dependency properties ​

PropertyTypeDefaultDescription
DisplayModeSidebarDisplayModeExpandedCurrent display mode
InnerContentUIElementnullMain content beside the pane (content property)
SidebarContentUIElementnullContent placed behind header, items, and footer inside the pane
HeaderUIElementnullPane header
FooterUIElementnullPane footer
PaneBackgroundBrushBrushnullBackground behind pane and content
IsPaneOpenboolfalsePane visibility in Minimal mode
OpenPaneLengthdouble240Pane width in Expanded mode
NegativeOpenPaneLengthdouble-240Maintained automatically by OpenPaneLength, used by animations
CanResizePanebooltrueEnables the resizer
SelectedItemISidebarItemModelnullThe selected model
MenuItemsSourceobjectnullSource for the flat item list
HoverToOpenDelayTimeSpanTimeSpan.ZeroHover time before a dragged-over item is invoked. Zero disables.
HoverToExpandDelayTimeSpanTimeSpan.ZeroHover time before a dragged-over item expands. Zero disables.
ExpanderStyleSidebarExpanderStyleTreeExpander presentation
ItemTemplateDataTemplatebuilt-inTemplate for rows

CLR property ​

PropertyTypeDefaultDescription
SupportsExpansionboolfalseNot a dependency property. When false, the chevron column collapses for every row. Set true for hierarchical sidebars.
VerticalScrollOffsetdouble (read-only)Current vertical scroll offset

Methods ​

MethodDescription
ScrollToVerticalOffset(double offset)Scrolls the item list without animation

Events ​

EventArgsRaised when
ItemInvokedItemInvokedEventArgsA row is clicked, activated with Enter, or invoked via automation
ItemContextInvokedItemContextInvokedArgsContext is requested on a row, or on empty space (Item is null)
ItemDragOverItemDragOverEventArgsData is dragged over a row
ItemDroppedItemDroppedEventArgsData is dropped on a row

Event payloads ​

csharp
public record ItemInvokedEventArgs(PointerUpdateKind PointerUpdateKind);
public record ItemContextInvokedArgs(object? Item, Point Position);
public record ItemDragOverEventArgs(object DropTarget, DataPackageView DroppedItem,
    SidebarItemDropPosition dropPosition, DragEventArgs RawEvent);
public record ItemDroppedEventArgs(object DropTarget, DataPackageView DroppedItem,
    SidebarItemDropPosition dropPosition, DragEventArgs RawEvent);

ItemDragOverEventArgs.DeferUntil(Task) keeps the drag-over open until the task completes, which allows asynchronous inspection of dragged data before setting AcceptedOperation.

Events fire with sender set to the SidebarItem for ItemInvoked and ItemContextInvoked, and to the SidebarView for ItemDragOver and ItemDropped. The drop target model is in the args.


SidebarItem ​

SidebarItem can be used inside SidebarView through the item template, or declared statically (for example, in Footer).

Dependency properties ​

PropertyTypeDefaultDescription
OwnerSidebarView?nullHosting view. Set by the repeater or parent row. Static items resolve it via a visual-tree walk.
ItemISidebarItemModel?nullBound model
IsSelectedboolfalseSelection state
IsExpandedbooltrueExpansion state. Synced to the model when UseItemPresentation is true.
NestingLevelint0Depth, drives IndentWidth
IndentWidthdouble0Computed from nesting level (16 px per level)
ContentOpacitydouble1.0Dims icon, text, chevron, and decorator only
IsInFlyoutboolfalseMarks rows rendered inside a compact-mode flyout
UseItemPresentationboolfalsePulls text, tooltip, icon, and decorator from the model
UseReorderDropboolfalseEnables top/bottom reorder drop zones. Computed in HandleItemChange.
IconFrameworkElement?nullRow icon
DecoratorFrameworkElement?nullTrailing decoration (for example, an eject button)
DisplayModeSidebarDisplayModeExpandedMirrors the owner's mode
TextstringnullRow label
ToolTipobject?nullExplicit tooltip

CLR properties ​

PropertyDescription
HasChildrentrue when Children is a non-empty list, or HasUnrealizedChildren is true
IsGroupHeadertrue when Item.Children is non-null
CollapseEnabledtrue unless the display mode is Compact

Tooltip behavior ​

A tooltip is resolved as follows:

  1. The explicit ToolTip, if set.
  2. Otherwise, Text when the label is hidden (compact mode, outside a flyout) or trimmed.
  3. Otherwise, none.

Keyboard ​

KeyAction
EnterInvoke the row
RightExpand if the row has children and is collapsed
LeftCollapse if the row has children and is expanded

Click behavior ​

Row typeRow clickChevron clickDouble-tap
Group headerToggles expansion (or opens flyout in compact mode); no selectionToggles expansionIgnored
Leaf with childrenInvokes and selectsToggles expansionToggles expansion
Regular leafInvokes and selectsn/an/a

Left and middle mouse button releases trigger a click. Other buttons do not.


Display Modes ​

csharp
public enum SidebarDisplayMode { Minimal, Compact, Expanded }
ModeBehavior
ExpandedPane width equals OpenPaneLength. Items can expand and collapse.
CompactPane width is SidebarCompactOpenPaneLength (56). Only icons show. Group headers with children open a flyout.
MinimalPane is hidden. Setting IsPaneOpen = true slides it over the content with a shadow and a light-dismiss layer.

Notes:

  • Entering Minimal forces IsPaneOpen = false.
  • Items in a flyout (IsInFlyout = true) never enter the Compact visual state, so their text stays visible.
  • The resizer is hidden in Minimal mode and when CanResizePane is false.

Expansion Behavior ​

Expander styles ​

StyleDescription
TreeChevron on the left, rows indented by NestingLevel * 16
GroupSection headings with a right-aligned chevron and muted, small heading text. Indent is max(0, NestingLevel - 1) * 16.

Chevron rotation ​

StateTreeGroup
Expanded90°-90°
Collapsed0°90°

Row types and their expansion states ​

ConditionState applied
SupportsExpansion is falseNoExpansion
No children list, or compact modeNoExpansion / GroupNoExpansion
Empty children, regular headerNoChildren / GroupNoChildren
Empty children, leaf with childrenNoExpansion / GroupNoExpansion
Has children, leaf with childrenLeafWithChildren
Has children, tree styleExpanded / Collapsed
Has children, group styleGroupExpanded / GroupCollapsed

Lazy loading ​

Return true from HasUnrealizedChildren for an item whose children load on first expansion. Raise PropertyChanged for HasUnrealizedChildren once loading completes, and for Children if the collection instance changes.


Selection ​

  • SidebarView.SelectedItem holds the selected model.
  • Selection is broadcast to every realized row from the dependency property callback, so rows that were prepared but not yet loaded cannot hold stale state.
  • Static SidebarItem instances outside the repeater (such as footer items) use a per-row property-changed callback instead.
  • Group headers are never selected, unless they are leaves with children.
  • When SelectedItem is a child of a collapsed group, the group header shows the selection indicator.
  • A row selected inside a flyout closes the flyout.

Drag and Drop ​

Drag source ​

A row is draggable when Item.Path is one of:

  • A rooted file system path
  • A path starting with Shell: (case-insensitive)
  • A path starting with ::{

Drag data provided:

  • Text: the path
  • StorageItems: the folder, when the path is an existing directory (via a data provider)
  • Requested operation: Move | Copy | Link

Drop target ​

Every row accepts drops on its ElementBorder. The drop position is determined as follows:

ConditionResult
UseReorderDrop is falseAlways Center
Reorder drag in progress (IsReorderDragActive)Top half → Top, bottom half → Bottom
Other drags, top 20%Top
Other drags, bottom 20%Bottom
Other drags, middleCenter

UseReorderDrop is true when the item is not a group header, is draggable, and CanReorder is true.

Handling drag over ​

Set AcceptedOperation and mark the event handled on RawEvent. The row only shows drop feedback when the event is handled and the operation is not None.

csharp
Sidebar.ItemDragOver += (s, e) =>
{
    e.RawEvent.AcceptedOperation = DataPackageOperation.Move;
    e.RawEvent.Handled = true;
};

Sidebar.ItemDropped += async (s, e) =>
{
    if (e.dropPosition == SidebarItemDropPosition.Center)
        await MoveIntoAsync(e.DropTarget, e.DroppedItem);
    else
        await ReorderAsync(e.DropTarget, e.DroppedItem, e.dropPosition);
};

For asynchronous checks:

csharp
Sidebar.ItemDragOver += (s, e) =>
{
    e.DeferUntil(EvaluateAsync(e));
};

Drop visuals ​

PositionVisual state
CenterDragOnTop (accent outline around the row)
TopDragInsertAbove (accent line at the top)
BottomDragInsertBelow (accent line at the bottom)

First-frame masking ​

The first drag-over frame of a drag session is ignored for visuals. A session is considered warm if the previous drag-over on the owning view occurred within 500 ms. This avoids flicker when a drag first enters the sidebar.

Hover timers ​

While a drag hovers over the center of a row:

TimerEnabled when
Hover to expand (HoverToExpandDelay)Delay is greater than zero, row has children, and expansion is allowed
Hover to open (HoverToOpenDelay)Delay is greater than zero, drop is accepted, row is not selected, and it is not a pure group header

Timers stop on drag leave and on drop.


Context Menus ​

ItemContextInvoked is raised for:

  • Rows, with Item set to the row model.
  • Empty areas of the scroll viewer, with Item set to null.

Position is relative to the row (or the view for empty areas). The event is marked handled so the default context behavior does not run.

csharp
Sidebar.ItemContextInvoked += (s, e) =>
{
    var flyout = BuildMenu(e.Item);
    flyout.ShowAt((FrameworkElement)s!, new FlyoutShowOptions { Position = e.Position });
};

Pane Resizing ​

The resizer is a 4 px wide element on the right edge of the pane with a horizontal-resize cursor.

InteractionResult
Drag below 200 pxSwitches to Compact
Drag above 200 pxSwitches to Expanded and sets OpenPaneLength
Double-tapToggles Expanded and Compact
Space / Enter in ExpandedSwitches to Compact
Space / Enter / Right in CompactSwitches to Expanded
Left / Right in ExpandedResizes by 1 px (5 px with Ctrl)

The pane column has a maximum width of 480. Resizing is disabled when CanResizePane is false.


Visual States Reference ​

SidebarView ​

GroupStates
DisplayModesExpanded, Compact, MinimalCollapsed, MinimalExpanded
ResizerStatesResizerNormal, ResizerPointerOver, ResizerPressed

Transitions between Compact/Expanded and the minimal states animate the pane translation over 0.35 s with a spline of 0.1,0.9 0.2,1.0.

SidebarItem ​

GroupStates
ExpansionStatesNoExpansion, NoChildren, Expanded, Collapsed, LeafWithChildren, GroupNoExpansion, GroupNoChildren, GroupExpanded, GroupCollapsed
ExpansionIconStatesExpandedIconNormal, ExpandedIconPressed, CollapsedIconNormal, CollapsedIconPressed, and the Group prefixed equivalents
SelectionStatesUnselected, Selected
PointerStatesNormal, NormalSelected, PointerOver, PointerOverSelected, Pressed, PressedSelected, DragOnTop
DragInsertStatesDragInsertNone, DragInsertAbove, DragInsertBelow
DisplayModesNonCompact, Compact
OwnerExpansionSupportOwnerSupportsExpansion, OwnerDoesNotSupportExpansion

State changes on rows are played without transitions, except drag and icon rotation states, to avoid animation churn during virtualization.


Template Parts ​

NameTypePurpose
RootPanelGridRoot, max width 48 in compact mode
ElementBorderBorderPointer and drag target, 32 px tall
ElementGridGridVisual row surface, tooltip owner, flyout anchor
SelectionIndicatorRectangleAccent bar
ChevronContainerBorderChevron click target
ExpandCollapseChevronFontIconChevron glyph (E76C)
ChevronColumnDefinitionColumnDefinition16 px chevron column
IconPresenterContentPresenterRow icon
ItemNameTextBlockTextBlockRow label, trimmed with ellipsis
ItemDecoratorPresenterContentPresenterTrailing decorator, 28 px wide
DragTargetIndicatorRectangleInsert line
DragOnTopIndicatorBorderDrop-into outline
FlyoutChildrenPresenterItemsRepeaterChildren inside the compact flyout

Parts used by code and hooked on template application: ElementBorder, ChevronContainer, FlyoutChildrenPresenter, ItemNameTextBlock, ElementGrid.


Theme Resources ​

Defined in SidebarStyles.xaml:

KeyValueUse
SidebarOpenPaneLength300Minimal mode pane width
SidebarNegativeOpenPaneLength-300Minimal slide offset
SidebarCompactOpenPaneLength56Compact pane width
SidebarNegativeCompactOpenPaneLength-56Compact slide offset
SidebarEjectButtonStyleStyle24 × 24 borderless button for decorators

Merge SidebarStyles.xaml into application resources so the default SidebarItem style resolves.


Accessibility ​

SidebarItemAutomationPeer ​

AspectValue
Control typeListItem
NameSidebarItem.Text
PatternsInvoke, SelectionItem, ExpandCollapse (only when collapse is enabled)
Expand stateExpanded, Collapsed, or LeafNode
Size of setNumber of siblings in the parent's Children or the view's MenuItemsSource
Position in setIndex of the row's DataContext in that collection, plus one

SidebarViewAutomationPeer ​

AspectValue
PatternSelection
CanSelectMultiplefalse
IsSelectionRequiredtrue
GetSelectionThe container of the selected item, when known

Each row's AutomationId is set to the model's Text when presentation is in use.


Implementation Notes ​

  • Owner assignment. MenuItemsHost_ElementPrepared sets Owner directly. A visual-tree search can find the wrong SidebarView when a sidebar is nested inside another sidebar's InnerContent, and recycled containers can carry a stale owner.
  • Template-time wiring. Handlers on template parts are attached in OnApplyTemplate, guarded by isTemplateWired. Loaded can fire before template parts exist.
  • Owner-level wiring. Property-changed subscriptions to the owner are attached once per container, guarded by isWiredUp. If Owner is still null on Loaded, wiring is retried on the next Loaded.
  • Recycling. HandleItemChange runs on every realization and on every Loaded. It resubscribes to the model, refreshes presentation, resets selection, and recomputes drag capability.
  • Section headers vs. leaves. Recycled containers reset IsSelected to false when bound to a header, preventing a stale selected paint.
  • Flyout rows. Rows in a flyout inherit Owner from the parent row and mirror selection state in FlyoutChildrenPresenter_ElementPrepared.
  • Flyout exceptions. ShowAttachedFlyout and GetAttachedFlyout can throw ArgumentException before the template is applied. These are swallowed.
  • COM exceptions. Drag data access and deferral completion catch COMException because the underlying drag session can end mid-operation.
  • Unhandled property changes. SidebarItem.OnPropertyChanged writes unhandled property names to the debug output.
  • Width setter. OpenPaneLength updates NegativeOpenPaneLength in its CLR setter, so assigning it from XAML or code keeps both in sync, while setting it through SetValue directly does not update the negative value.

Troubleshooting ​

SymptomLikely causeFix
Rows have no chevronSupportsExpansion is falseSet SupportsExpansion = true
Chevron present but never rotatesModel IsExpanded change not raising PropertyChangedRaise PropertyChanged for IsExpanded
Group header does not expand on clickRow is a leaf with childrenClick the chevron, or toggle IsExpanded in code
Multiple rows appear selectedSelectedItem not reference-equal to the row's modelUse the same instance in SelectedItem and the item list
Section headings lack spacingHasExpandedPredecessor not setSet it on the flat item following an expanded section
Depth indent changes don't applyDepth is immutable on FlatSidebarItemCreate a new wrapper
Drop feedback never showsItemDragOver doesn't set AcceptedOperation and HandledSet both on RawEvent
Drag does not startPath is not rooted, Shell:, or ::{Provide a supported path
Compact flyout does not openItem Children is null or emptyProvide a non-empty children collection
Default style not appliedSidebarStyles.xaml not merged, or its local: namespace does not point to DevWinUIMerge the dictionary and confirm the xmlns:local mapping targets the SidebarItem type
Hover-to-open does nothingDelay properties default to zeroSet HoverToOpenDelay and HoverToExpandDelay

SidebarView

Demo ​

you can run demo and see this feature.

Released under the MIT License.