Share via

Opening folder picker

Eduardo Gomez 4,316 Reputation points
2026-02-19T20:58:45.13+00:00

Wainui does not let me

I have a window and 2 pages

Main Window

<Grid>

    <NavigationView
        x:Name="NavView"
        IsBackButtonVisible="Collapsed"
        IsSettingsVisible="False"
        IsTabStop="True"
        PaneDisplayMode="Left"
        SelectionChanged="NavigationView_SelectionChanged">

        <!--  Frame for content  -->
        <Frame x:Name="contentFrame" />
    </NavigationView>

</Grid>

public sealed partial class MainWindow : Window {
    public MainWindowViewModel ViewModel { get; }
    public MainWindow(MainWindowViewModel vm, INavigationService navigationService) {
        InitializeComponent();
        ViewModel = vm;
        navigationService.Initialize(contentFrame);
        foreach(var menuItem in ViewModel.MenuItems) {
            NavView.MenuItems.Add(new NavigationViewItem {
                Content = menuItem.Title,
                Icon = new SymbolIcon(menuItem.Icon),
                Tag = menuItem
            });
        }
        NavView.SelectedItem = NavView.MenuItems[1];
    }
    private void NavigationView_SelectionChanged(NavigationView sender, NavigationViewSelectionChangedEventArgs args) {
        if(args.SelectedItemContainer?.Tag is NavItem item) {
            ViewModel.NavigateTo(item);
        }
    }
}

public partial class MainWindowViewModel(INavigationService navigationService) : ObservableObject {
    public ObservableCollection<NavItem> MenuItems { get; } = MenuService.GetMenuItems();
    public void NavigateTo(NavItem item) {
        if(item is not null) {
            navigationService.Navigate(item.PageType);
        }
    }
}


Now I have a page, where I want to open a folder picker, and I need it to be fast

using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System.Threading.Tasks;
using FolderPicker = Windows.Storage.Pickers.FolderPicker;
namespace EasyShere.ViewModel;
public partial class BuildPageViewModel : ObservableObject {
    [ObservableProperty]
    public partial bool IsButtonEnabled { get; set; } = true;
    [ObservableProperty]
    public partial string Path { get; set; }
    [RelayCommand]
    async Task OpenFolder() {
        var folderPicker = new FolderPicker();
        var FolderLocation = await folderPicker.PickSingleFolderAsync();
        if(FolderLocation != null) {
            Path = FolderLocation.Path;
        }
    }
}

but when I try to open I get

System.Runtime.InteropServices.COMException: 'Invalid window handle. (0x80070578)
Consider WindowNative, InitializeWithWindow
See https://aka.ms/cswinrt/interop#windows-sdk'

But I don't know where to get the window from

Since I want to open it ibn a page

code

https://github.com/eduardoagr/EasyShere

Windows development | WinUI

3 answers

Sort by: Most helpful
  1. Jack Dang (WICLOUD CORPORATION) 18,145 Reputation points Microsoft External Staff Moderator
    2026-02-20T07:55:46.6566667+00:00

    Hi @Eduardo Gomez ,

    Thanks for reaching out.

    The FolderPicker in WinUI 3 needs to be initialized with a window handle before you can call PickSingleFolderAsync(). Without this, you'll get that COMException: Invalid window handle (0x80070578) error.

    The tricky part here is that your BuildPageViewModel is sitting inside a page that's hosted in a frame, so it doesn't have direct access to the main window. To solve this while keeping your MVVM architecture clean, I'd recommend creating a simple service that provides the window handle to any component that needs it.

    What I'd do is:

    1. Create an interface for the window service

    Create Interfaces/IWindowService.cs:

    namespace EasyShere.Interface;
    
    public interface IWindowService {
        nint GetWindowHandle();
    }
    
    1. Implement the service

    Create Services/WindowService.cs:

    using EasyShere.Interface;
    
    namespace EasyShere.Services;
    
    public class WindowService : IWindowService {
    
        private nint _windowHandle;
    
        public void Initialize(Window window) {
            _windowHandle = WinRT.Interop.WindowNative.GetWindowHandle(window);
        }
    
        public nint GetWindowHandle() {
            if(_windowHandle == 0) {
                throw new InvalidOperationException("Window handle not initialized. Call Initialize() first.");
            }
            return _windowHandle;
        }
    }
    
    1. Register it in your DI container

    Update App.xaml.cs in the ConfigureServices method:

    services.AddSingleton<WindowService>();
    services.AddSingleton<IWindowService>(sp => sp.GetRequiredService<WindowService>());
    
    1. Initialize it when the app launches

    In App.xaml.cs, update the OnLaunched method:

    protected override void OnLaunched(LaunchActivatedEventArgs args) {
        _window = Services.GetRequiredService<MainWindow>();
    
        var windowService = Services.GetRequiredService<WindowService>();
        windowService.Initialize(_window);
    
        _window.ExtendsContentIntoTitleBar = true;
        _window.Activate();
    }
    
    1. Use it in your ViewModel

    Update BuildPageViewModel.cs:

    using CommunityToolkit.Mvvm.ComponentModel;
    using CommunityToolkit.Mvvm.Input;
    using EasyShere.Interface;
    using System.Threading.Tasks;
    using FolderPicker = Windows.Storage.Pickers.FolderPicker;
    
    namespace EasyShere.ViewModel;
    
    public partial class BuildPageViewModel : ObservableObject {
    
        private readonly IWindowService _windowService;
    
        public BuildPageViewModel(IWindowService windowService) {
            _windowService = windowService;
        }
    
        [ObservableProperty]
        public partial bool IsButtonEnabled { get; set; } = true;
    
        [ObservableProperty]
        public partial string Path { get; set; }
    
        [RelayCommand]
        async Task OpenFolder() {
            var folderPicker = new FolderPicker();
    
            var hwnd = _windowService.GetWindowHandle();
            WinRT.Interop.InitializeWithWindow.Initialize(folderPicker, hwnd);
    
            var FolderLocation = await folderPicker.PickSingleFolderAsync();
    
            if(FolderLocation != null) {
                Path = FolderLocation.Path;
            }
        }
    }
    

    Hope this helps! If my answer was helpful - kindly follow the instructions here so others with the same problem can benefit as well.

    Was this answer helpful?

    0 comments No comments

  2. Castorix31 91,871 Reputation points
    2026-02-19T23:56:38.0933333+00:00

    You can change in App.xaml.cs :

     public static Window? _window;
    
    

    Then :

      var folderPicker = new FolderPicker();
      folderPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.ComputerFolder;
      folderPicker.FileTypeFilter.Add("*");
      var hWnd = WinRT.Interop.WindowNative.GetWindowHandle(App._window);
      WinRT.Interop.InitializeWithWindow.Initialize(folderPicker, hWnd);
      var FolderLocation = await folderPicker.PickSingleFolderAsync();
    
    

    Was this answer helpful?

    0 comments No comments

  3. Q&A Assist
    2026-02-19T20:58:57.7+00:00
    AI generated content. This question contains an answer created with AI from Q&A Assist. Learn more

    To open a folder picker in a WinUI application, you can use the FolderPicker class. This allows users to select a folder from their file system. Here’s a basic example of how to implement it:

    using Microsoft.Windows.Storage.Pickers;
    
    var folderPicker = new FolderPicker();
    folderPicker.SuggestedStartLocation = PickerLocationId.Desktop;
    folderPicker.FileTypeFilter.Add("*"); // Allows all file types
    
    StorageFolder folder = await folderPicker.PickSingleFolderAsync();
    if (folder != null)
    {
        // Use the selected folder
    }
    else
    {
        // Handle the case when the user cancels the picker
    }
    

    Make sure that your application has the necessary permissions to access the file system. If you are experiencing issues with the picker not opening, ensure that you are calling the picker from the UI thread and that your app is set up correctly to handle the picker dialogs.


    References:

    Was this answer helpful?

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.