Skip to content

Custom save file dialog

FantasticFiasco edited this page Dec 13, 2017 · 3 revisions

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

public class CustomSaveFileDialog : 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 CreateSaveFileDialog(SaveFileDialogSettings settings)
    {
        return new CustomSaveFileDialog(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 save file dialogs.

<UserControl
    x:Class="DemoApplication.Features.SaveFileDialog.Views.SaveFileTabContent"
    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.ShowSaveFileDialog.

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

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