New to Telerik UI for WPF? Download free 30-day trial

Open File Dialogs from View Model

Environment

Product Version 2020.2.617
Product RadFileDialogs for WPF

Description

How to open the RadFileDialogs using an MVVM-friendly approach through the viewmodel.

Solution

You can start by creating a service class similar to the one in Example 1 which will be responsible for opening the window. If needed, you can also introduce an interface with a single OpenFileDialog method and have the OpenFileDialogService class implement this interface.

Example 1: The OpenFileDialogService class

public class OpenFileDialogService 
{ 
    public string OpenFileDialog() 
    { 
        RadOpenFileDialog openFileDialog = new RadOpenFileDialog(); 
        openFileDialog.Filter = "All Files (.)|."; 
        openFileDialog.FilterIndex = 1; 
        openFileDialog.Multiselect = false; 
        openFileDialog.ShowDialog(); 
 
        if (openFileDialog.DialogResult == true) 
        { 
            return openFileDialog.FileName; 
        } 
 
        return string.Empty; 
    } 
} 
You can now define a command in your view model which uses this service and its method.

Example 2: Defining the viewmodel

public class MainViewModel : ViewModelBase 
{ 
    private OpenFileDialogService fileDialogService; 
 
    public MainViewModel() 
    { 
        this.fileDialogService = new OpenFileDialogService(); 
        this.OpenFileDialogCommand = new DelegateCommand(OnOpenFileDialog); 
    } 
 
    public ICommand OpenFileDialogCommand { get; set; } 
 
    private void OnOpenFileDialog(object obj) 
    { 
        var fileName = fileDialogService.OpenFileDialog(); 
    } 
} 
Finally, you need to invoke this command from your view.

Example 3: Binding the command in the view

<Grid> 
    <Grid.DataContext> 
        <local:MainViewModel /> 
    </Grid.DataContext> 
    <telerik:RadButton Command="{Binding OpenFileDialogCommand}" Content="Open Dialog" /> 
</Grid> 

See Also

In this article