Skip to content

Custom open file dialog

FantasticFiasco edited this page Oct 31, 2021 · 3 revisions

To show a custom open file dialog start by implementing IFrameworkDialog.

public class CustomOpenFileDialog : IFrameworkDialog
{
    ...
}

Next up is the implementation of the custom framework dialog factory, responsible for creating framework dialogs opened by DialogService.

public class CustomFrameworkDialogFactory : DefaultFrameworkDialogFactory
{
    public override IFrameworkDialog CreateOpenFileDialog(OpenFileDialogSettings settings)
    {
        return new CustomOpenFileDialog(settings);
    }
}

At this point we have a complete implementation of a custom framework dialog factory. Next up is providing it to DialogService.

How that is done depends on the application. If you are using an IoC container you would configure the container to inject the factory when the container is resolving the dialog service. If you are running on bare metal you would configure this wherever you initialize your application.

For this application, lets assume that we are creating the dialog service in MainWindowViewModel.

public class MainWindowViewModel : INotifyPropertyChanged
{
    private readonly IDialogService dialogService;

    public MainWindowViewModel()
    {
        var frameworkDialogFactory = new CustomFrameworkDialogFactory();
        dialogService = new DialogService(frameworkDialogFactory: frameworkDialogFactory);
    }
    ...
}

We now have the dialog service configured to use the custom framework dialog factory. The following steps are the same for standard open file dialogs.

<UserControl
    x:Class="DemoApplication.Features.OpenFileDialog.Views.OpenFileTabContent"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:md="https://github.com/fantasticfiasco/mvvm-dialogs"
    md:DialogServiceViews.IsRegistered="True">
  
</UserControl>

In the view model, open the dialog by calling IDialogService.ShowOpenFileDialog.

public class OpenFileTabContentViewModel : INotifyPropertyChanged
{
    private readonly IDialogService dialogService;
  
    public OpenFileTabContentViewModel(IDialogService dialogService)
    {
        this.dialogService = dialogService;
    }
  
    private void OpenFile()
    {
        var settings = new OpenFileDialogSettings
        {
            Title = "This Is The Title",
            InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
            Filter = "Text Documents (*.txt)|*.txt|All Files (*.*)|*.*"
        };

        bool? success = dialogService.ShowOpenFileDialog(this, settings);
        if (success == true)
        {
            Path = settings.FileName;
        }
    }
}