It is necessary functionality whenever we want to select and add any file in our project.

Writing the open file code on button event in code behind, we know. But writing the code in MVVM model is the new form for some developer, so we are working on it step by step.
 To know more about creating MVVM design pattern please click on link Creating MVVM pattern design

What explorer we use for open file in MVVM?

In windows form for opening file we use the openfiledialog box. But here we didn’t use any dialog box control. We simply write the logic on viewmodel and here we used the OpenFileDialog class.
And call that code on button command property.
Let’s go for step by step

Step By Step Adding of classes in WPF MVVM:

First add four folder namely

Command, 2) Images, 3) ViewModel and 4)View

Step 1: Right click on folder Command and add a class named RelayCommand

Step 2: Right click Images folder and add openfolder appropriate image, download from google.

Step 3: Right click on folder ViewModel and add two class named as OpenFileViewModel and ViewModelBase.

Step 4: Right click on folder View and add OpenFileView

Write Code on respective classes each shown below with namespace
RelayCommand.cs

Add namespace
using System.Windows.Input;

namespace OpenFileMVVM.Command
{
    public class RelayCommand : ICommand
    {
        private Action DoWork;

        public RelayCommand(Action work)
        {
            DoWork = work;
        }

        public bool CanExecute(object parameter)
        {
            return true;
        }

        public event EventHandler CanExecuteChanged;

        public void Execute(object parameter)
        {
            DoWork();
        }
    }
}


OpenFileViewModel.cs
Add below Namespace and code
using System.Windows.Input;
using Microsoft.Win32;
using System.IO;
using OpenFileMVVM.ViewModels;
using OpenFileMVVM.Command;

 namespace OpenFileMVVM.ViewModel
{
    public class OpenFileViewModel : ViewModelBase
    {

        private readonly ICommand _openFileCommand;

        public ICommand OpenFileCommand
        {
            get { return _openFileCommand; }
        }

        private string txtEditor;

        public string TxtEditor
        {
            get { return txtEditor; }
            set { SetProperty(ref txtEditor, value); }
        }

        private string filePath;

        public string FilePath
        {
            get { return filePath; }
            set { SetProperty(ref filePath, value); }
        }

        public OpenFileViewModel()
        {
            CanOpenFile = true;
            _openFileCommand = new RelayCommand(SelectPartPath);
        }

        public static bool CanOpenFile { get; private set; }

        public void SelectPartPath()
        {
            OpenFileDialog importFileDialog1 = new OpenFileDialog();

            // Set filter for file extension and default file extension
            string theFilter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";


            importFileDialog1.DefaultExt = ".txt";
            importFileDialog1.Filter = theFilter;

            if (importFileDialog1.ShowDialog() == true)
            {
                TxtEditor = File.ReadAllText(importFileDialog1.FileName);
            }

            FilePath = importFileDialog1.FileName;
        }
    }
}


ViewModelBase.cs

Add namespace and code

using System.ComponentModel;

namespace OpenFileMVVM.ViewModels
{
    public abstract class ViewModelBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        protected bool SetProperty<T>(ref T field, T newValue, [CallerMemberName]string propertyName = null)
        {
            if (!EqualityComparer<T>.Default.Equals(field, newValue))
            {
                field = newValue;

                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
                }
                return true;
            }
            return false;
        }
    }
}

OpenFileView.xaml

<Window x:Class="OpenFileMVVM.View.OpenFileView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc=http://schemas.openxmlformats.org/markup-compatibility/2006
        xmlns:local="clr-namespace:OpenFileMVVM.View"
        xmlns:ViewModels="clr-namespace:OpenFileMVVM.ViewModel"
        Title="OpenFileView">

    <Window.Resources>
        <Style x:Key="GridStyle1" TargetType="{x:Type Grid}"/>
    </Window.Resources>
    <Window.DataContext>
        <ViewModels:OpenFileViewModel x:Name="vm"/>
    </Window.DataContext>

    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="4" />
        </Grid.ColumnDefinitions>   

        <Grid.RowDefinitions>
            <RowDefinition Height="1*" />
            <RowDefinition Height="1*" />
            <RowDefinition Height="1*" />
        </Grid.RowDefinitions>   

        <Border Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2" Padding="32,42,21,0">
            <GroupBox Header="File Name" Foreground="#ed6f21" Height="60">
                <Grid>

                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="28*" />
                        <ColumnDefinition Width="29*"/>
                        <ColumnDefinition Width="40*"/>
                        <ColumnDefinition Width="84*"/>
                        <ColumnDefinition Width="46" />
                    </Grid.ColumnDefinitions>

                    <Grid.RowDefinitions>
                        <RowDefinition Height="46" />
                    </Grid.RowDefinitions>

                    <TextBox BorderThickness="0" Grid.Column="0" Grid.ColumnSpan="5" Height="21px" FontSize="16px" FontWeight="Normal" Text="{Binding FilePath, Mode=TwoWay}" Margin="4,9,42,16"/>
                    <Button Grid.Column="4" Background="Transparent" BorderThickness="0" Command="{Binding Path=OpenFileCommand}"
                        Margin="0,-6,0,6">
                        <Image Width ="20" Height="20" Source="/Images/folder.png"  VerticalAlignment="Center" HorizontalAlignment="Center"/>
                    </Button>
                </Grid>
            </GroupBox>
        </Border>     

        <Border Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2" Padding="32,42,21,0">
     <GroupBox Header="Opened File" Foreground="#ed6f21" Height="150" Margin="0,-32,0,28">
                <TextBox BorderThickness="0" FontSize="16px" FontWeight="Normal" Text="{Binding TxtEditor, Mode=TwoWay}"/>
          </GroupBox>
        </Border>
    </Grid>
</Window>

After writing above code in respective file.
Right click on App.xaml file from solution explorer à click on ViewDesigner.

Change the above code StartupUri=”MainWindow.xaml” to StartupUri=” View/OpenFileView.xaml”
Run the application the output should be like below

Open file design

Click on openfolder button in file name and select the text file then the result should be look like below screen shots


Open and read notepad file

Please feel free to share your quarries in comment.

Post a Comment

أحدث أقدم