WPF MVVM JSON Operations (Part - II : Write data to Json File)

 WPF MVVM JSON Operations (Part - II :  Write data to Json File)

Part-II :  Read/Accept Data From UI/ Xmal and Write/Save it to Json File

Following is the the folder structure & Source Code



Folder: View - > MainWindow.xaml

<Window x:Class="WpfJsonDataReader.MainWindow"

        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:WpfJsonDataReader"

        xmlns:vm="clr-namespace:WpfJsonDataReader.ViewModel"

        mc:Ignorable="d"

        Title="MainWindow" Height="350" Width="525">

    <Window.Resources>

        <vm:PersonViewModel x:Key="ViewModel"/>

    </Window.Resources>

   

    <Grid  DataContext="{Binding Source={StaticResource ViewModel}}">

        <Grid.RowDefinitions>

            <RowDefinition Height="auto"/>

            <RowDefinition Height="auto"/>

            <RowDefinition Height="auto"/>

            <RowDefinition Height="*"/>

        </Grid.RowDefinitions>

 

        <Label Grid.Row="0" Content="WPF MVVM Pattern: CRUD Operations on Json" HorizontalAlignment="Center" FontSize="15" Background="AntiqueWhite"/>

       

        <Grid Grid.Row="1" Background="BlanchedAlmond">

            <Grid.RowDefinitions>

                <RowDefinition Height="30"/>

            </Grid.RowDefinitions>

           

            <Button Content="Show"  HorizontalAlignment="Left" Margin="194,5,0,5" Height="20" Width="60" Command="{Binding ShowDataCommand}"/>

            <Button Content="Add" HorizontalAlignment="Left" Margin="2,5,0,5" Height="20" Width="60" Command="{Binding AddCommand}"/>

        </Grid>

        <Grid Grid.Row="2" >

            <Grid ShowGridLines="False">

                <Grid.ColumnDefinitions>

                    <ColumnDefinition Width="*" />

                    <ColumnDefinition  Width="*"/>

                    <ColumnDefinition  Width="*"/>

                    <ColumnDefinition  Width="*"/>

                </Grid.ColumnDefinitions>

                <Grid.RowDefinitions>

                    <RowDefinition Height="Auto"/>

                    <RowDefinition Height="Auto"/>

                    <RowDefinition Height="Auto" />

                </Grid.RowDefinitions>

 

                <Label  Grid.Column="0" Grid.Row="0" Content="First Name:"  HorizontalAlignment="Right"  />

                <TextBox Grid.Column="1"  Grid.Row="0" x:Name="FirstNametxt"

                         Text="{ Binding SelectedPersonModel.FirstName ,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"

                         HorizontalAlignment="Left" MinWidth="100" VerticalAlignment="Center"     />

                <Label Grid.Column="2" Grid.Row="0"  Content="Last Name:"  HorizontalAlignment="Right" Width="89" HorizontalContentAlignment="Right" />

                <TextBox Grid.Row="0"  Grid.Column="3" Name="LastNametxt"

                         Text="{ Binding SelectedPersonModel.LastName,Mode=TwoWay}"

                         HorizontalAlignment="Left"  Margin="0,6,0,5" MinWidth="100"  />

 

                <Label  Grid.Row="1" Grid.Column="0"  Content="Age:" HorizontalAlignment="Right" Width="103"  HorizontalContentAlignment="Right"/>

                <TextBox Grid.Row="1" Grid.Column="1"  Name="Agetxt"  HorizontalAlignment="Left"

                         Text="{ Binding SelectedPersonModel.Age ,Mode=TwoWay}"

                         Width="102" Margin="0,7"  />

                <Label  Grid.Row="1" Grid.Column="2" Content="Contact Number:"  HorizontalAlignment="Right" Width="108" HorizontalContentAlignment="Right"/>

                <TextBox Grid.Row="1" Grid.Column="3"  Name="contacttxt"  HorizontalAlignment="Left"

                         Text="{ Binding SelectedPersonModel.Number ,Mode=TwoWay}"

                         Width="102" Margin="0,7"  />               

               

 

            </Grid>

        </Grid>

 

        <DataGrid x:Name="UsersDataGrid" Grid.Row="3" AutoGenerateColumns="False" ItemsSource="{Binding Items}"

                  HorizontalAlignment="Stretch" VerticalAlignment="Stretch"

                  ScrollViewer.VerticalScrollBarVisibility="Visible" CanUserAddRows="False" SelectedItem="{Binding SelectedPersonModel}" >           

            <DataGrid.Columns>

                <DataGridTextColumn Header="First Name" Width="100" Binding="{Binding FirstName}" />

                <DataGridTextColumn Header="Last Name" Width="100" Binding="{Binding LastName}" />

                <DataGridTextColumn Header="Age" Width="100" Binding="{Binding Age}" />

                <DataGridTextColumn Header="Number" Width="100" Binding="{Binding Number}" />

 

            </DataGrid.Columns>

           

        </DataGrid>

       

    </Grid>

</Window>

 

Folder: Model - > PersonModel.cs

public class PersonModel:NotifyPropertyChangedHandler

    {

        private string firstname;

 

        public string FirstName

        {

            get { return firstname; }

            set { firstname = value; NotifyPropertyChanged("FirstName"); }

        }

 

        private string lastname;

 

        public string LastName

        {

            get { return lastname; }

            set { lastname = value; NotifyPropertyChanged("LastName"); }

        }

 

         private int age;

 

        public int Age

        {

            get { return age; }

            set { age = value; NotifyPropertyChanged("Age"); }

        }

 

        private double number;

 

        public double Number

        {

            get { return number; }

            set { number = value; NotifyPropertyChanged("Number"); }

        }

 

       

    }

Folder: ViewModel - > NotifyPropertyChangedHandler.cs

public class NotifyPropertyChangedHandler : INotifyPropertyChanged

    {

        public event PropertyChangedEventHandler PropertyChanged;

        protected void NotifyPropertyChanged(string propertyName)

        {

            if (PropertyChanged != null)

            {

                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));

            }

        }

    }

Folder: ViewModel - > PersonViewModel.cs

public class PersonViewModel: NotifyPropertyChangedHandler

    {

       

        private ICommand _ShowDataCommand;

        private ICommand _AddCommand;

        private PersonModel _SelectedPersonModel;

        public PersonModel SelectedPersonModel

        {

            get { return _SelectedPersonModel; }

            set { _SelectedPersonModel = value; NotifyPropertyChanged("SelectedPersonModel"); }

        }

 

       

   

        private List<PersonModel> _Items;

        public List<PersonModel> Items

        {

            get { return _Items; }

            set { _Items = value; NotifyPropertyChanged("Items"); }

        }

 

      

 

        public PersonViewModel()

        {

        SelectedPersonModel = new PersonModel();

        }

        /// <summary>

        /// Show Json File to Grid via List

        /// </summary>

        public ICommand ShowDataCommand

        {

            get

            {

                if (_ShowDataCommand == null)

                {

                    _ShowDataCommand = new RelayCommand(param => this.GetJsonData(), null);

                }

                return _ShowDataCommand;

            }

        }

        private void GetJsonData()

        {

            string json = System.IO.File.ReadAllText(@"PeopleData.json");

            Items = JsonConvert.DeserializeObject<List<PersonModel>>(json);

        }

        //-----------

        public ICommand AddCommand

        {

            get

            {

                if(_AddCommand == null)

                {

                    _AddCommand = new RelayCommand(param => this.AddJsonData(), null);

                }

                return _AddCommand;

            }

        }

        private void AddJsonData()

        {

            Items.Add(SelectedPersonModel);

            var NewJsonData = JsonConvert.SerializeObject(Items, Formatting.Indented);

            File.WriteAllText(@"PeopleData.json", NewJsonData);

        }

 

    }

Folder: ICommandUpdater- > NotifyPropertyChangedHandler.cs

public class RelayCommand:ICommand

    {

        public RelayCommand(Action<object> execute) : this(execute, null)

        {    }

 

    public RelayCommand(Action<object> execute, Predicate<object> canExecute)

    {

        if (execute == null)

            throw new ArgumentNullException("execute");

        _execute = execute;

        _canExecute = canExecute;

    }

    public bool CanExecute(object parameter)

    {

        return _canExecute == null ? true : _canExecute(parameter);

    }

    public event EventHandler CanExecuteChanged

    {

        add { CommandManager.RequerySuggested += value; }

        remove { CommandManager.RequerySuggested -= value; }

    }

    public void Execute(object parameter)

    {

        _execute(parameter);

    }

    private readonly Action<object> _execute;

    private readonly Predicate<object> _canExecute;

}

Project Folder: *\bin\Debug\ PeopleData.json

[

  {

    "FirstName": "Joe",

    "LastName": "Jackson",

    "Age": 28,

    "Number": 7349282382.0

  },

  {

    "FirstName": "James",

    "LastName": "Smith",

    "Age": 32,

    "Number": 5678568567.0

  },

  {

    "FirstName": "Emily",

    "LastName": "Jones",

    "Age": 24,

    "Number": 456754675.0

  },

  {

    "FirstName": "ABC",

    "LastName": "new",

    "Age": 32,

    "Number": 77765789.0

  },

  {

    "FirstName": "Person1",

    "LastName": "Last",

    "Age": 20,

    "Number": 333550.0

  }

]

Final UI->  Output Window



Comments

Post a Comment

Popular posts from this blog

Simple WPF MVVM Application with Unit Testing.

WPF MVVM JSON Operations (Part - I : Read Json File Data to List and Show on Xmal using DataGrid )