Click here to Skip to main content
15,890,438 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have a ListBox which when I select an Item then click delete button the changes do not show immediately until I exit the app then start it up again. The changes reflect only when I have done that. Same goes for my saving button on the second window when I click save my listbox does not update the newly added Item until I exit the app and back to it again that is when I Will see what I have added.

What I have tried:

ViewModel for my first MainWindow
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using PhoneBook.View;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;

namespace PhoneBook.ViewModel
{
    class MainWindowViewModel : ViewModelBase
    {
        #region Constructor
        public MainWindowViewModel()
        {
            ReadTextFile();
        }

        #endregion
        #region Properties
        public const string MyListPropertyName = "ListBox";
        private ObservableCollection<string> _contactDetails = null;
        public ObservableCollection<string> ContactDetails
        {
            get
            {
                return _contactDetails = _contactDetails ?? new ObservableCollection<string>();
            }
            set
            {
                if (_contactDetails == value)
                {
                    return;
                }
                RaisePropertyChanged(MyListPropertyName);
                _contactDetails = value;
                RaisePropertyChanged(MyListPropertyName);
            }
          
          
        }
        private string _selectedContact = null;
        public string SelectedContact
        {
            get
            {
                return _selectedContact;
            }
            set
            {
                if (_selectedContact != null)
                {
                    return;
                }
                _selectedContact = value;
                RaisePropertyChanged();
            }
        }



        #endregion

        #region Method


        string FileName = (@"C: \Users\StanleyM\Desktop\PhoneBook\PhoneBook\bin\Debug\Personal.text");
        private void DeleteSelectedItemListBox()
        {

            var deletingNumber = ContactDetails.IndexOf(SelectedContact);
            var allLines = File.ReadAllLines(FileName).ToList();
            allLines.RemoveAt(deletingNumber);
            File.WriteAllLines(FileName, allLines.ToArray());


            RaisePropertyChanged(propertyName: "ListBox");

        }

        public void ReadTextFile()
        {
            string FileName = (@"C: \Users\StanleyM\Desktop\PhoneBook\PhoneBook\bin\Debug\Personal.text");
            StreamReader streamReader = new StreamReader(FileName);
            string line = "";
            int Counter = 0;
            while ((line = streamReader.ReadLine()) != null)
            {
                Counter++;
                ContactDetails.Add(item: line);
            }
            RaisePropertyChanged("ListBox");
        }

        private void PopUpWindow()
        {
            AddEditView PopUp = new AddEditView();
            PopUp.ShowDialog();

        }


        #endregion
        #region RelayCommand

        private RelayCommand _addCommand = null;
        public RelayCommand AddCommand
        {
            get
            {
                return _addCommand = _addCommand ?? new RelayCommand(() => PopUpWindow());
            }
        }

        private RelayCommand _deleteCommand = null;
        public RelayCommand DeleteCommand
        {
            get
            {
                return _deleteCommand = _deleteCommand ?? new RelayCommand(() => DeleteSelectedItemListBox());
            }
        }


        #endregion
    }
}



First View
<Window x:Class="PhoneBook.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:PhoneBook"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    
    <Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="/PhoneBook;component/Resource/Resource.xaml"></ResourceDictionary>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Window.Resources>
    <Border BorderThickness="5" BorderBrush="AliceBlue" Background="AntiqueWhite">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>

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

            </Grid.RowDefinitions>
            <Label Grid.Row="0" Content="List of Clients" ></Label>
            <Border Grid.Row="1" BorderThickness="5" Background="Black">
                <ListBox SelectedItem="{Binding SelectedContact, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" 
                         ItemsSource="{Binding ContactDetails, UpdateSourceTrigger=PropertyChanged, NotifyOnSourceUpdated=True, Mode=TwoWay}" 
                         Grid.Row="1">
                </ListBox>
            </Border>

            <Button Grid.Row="1"
                    Grid.Column="1" Width="75"
                    Height="25" VerticalAlignment="Top"
                    Margin="100 10 0 0" HorizontalAlignment="Left"
                    Content="Add" Command="{Binding AddCommand}"></Button>
            <Button Grid.Row="1"
                    Grid.Column="1"
                    Width="75" Height="25"
                    VerticalAlignment="Top"
                    Margin="100 60 0 0"
                    HorizontalAlignment="Left"
                    Content="Delete"
                    x:Name="Deletebtn" Click="Deletebtn_Click"
                    Command="{Binding DeleteCommand}"></Button>
        </Grid>
    </Border>
</Window>



ViewModel For my second window

using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using PhoneBook.Class;
using PhoneBook.View;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace PhoneBook.ViewModel
{
    class AddEditViewModel : ViewModelBase
    {
        #region Construtors
        public AddEditViewModel()
        {
            PopulateDropDown();
        }
        #endregion
        #region Properties
        private List<_Title> _titles = null;
        public List<_Title> Titles
        {
            get
            {
                return _titles = _titles ?? new List<_Title>();
            }
        }

        private _Title _selectedTitle = null;
        public _Title SelectedTitle
        {
            get
            {
                return _selectedTitle;
            }
            set
            {
                _selectedTitle = value;
                RaisePropertyChanged();
            }
        }

        private List<_Gender> _genders = null;
        public List<_Gender> Genders
        {
            get
            {
                return _genders = _genders ?? new List<_Gender>();
            
            }
        }

        private _Gender _selectedGender = null;
        public _Gender SelectedGender
        {
            get
            {
                return _selectedGender;
            }
            set
            {
                _selectedGender = value;
                RaisePropertyChanged();

            }
        }

        private string _firstName = null;
        public string FirstName
        {
            get
            {
                return _firstName;
            }
            set
            {
                _firstName = value;
                RaisePropertyChanged();
            }
        }


        private string _lastName = null;
        public string LastName
        {
            get
            {
                return _lastName;
            }
            set
            {
                _lastName = value;
                RaisePropertyChanged();
            }
        }

        private string _email = null;
        public string Email
        {
            get
            {
                return _email;
            }
            set
            {
                _email = value;
                RaisePropertyChanged();
            }
        }

        private int _phoneNumber;
        public int PhoneNumber
        {
            get
            {
                return _phoneNumber;
            }
            set
            {
                _phoneNumber = value;
                RaisePropertyChanged();
            }
        }

        
        #endregion

        #region Method
        private void CloseWindow()
        {
            AddEditView add = new AddEditView();
            add.Close();
        }

           

        private void SaveDetails()
        {
            string Title = "";
            string Gender = "";

            int number = 0000000000;
            if (SelectedTitle == null)
                {
                MessageBox.Show("Please select Title");
                }
                else if (FirstName == null)
                {
                    MessageBox.Show("Please input First Name");
                }
                else if (LastName == null)
                {
                    MessageBox.Show("Please input last Name");
                }
                else if (Email == null)
                {
                    MessageBox.Show("Please input emaill");
                }
                else if (PhoneNumber != number )
                {
                    MessageBox.Show("Only nunmbers allowed");
                }
                else if(SelectedGender == null)
                {
                    MessageBox.Show("Please select Gender");
                }
                else if (true)
                {
               
                foreach (var item in Titles)
                {
                    Title = item.Title = SelectedTitle.Title;
                }


                
                foreach (var item in Genders)
                {
                    Gender = item.Gender = SelectedGender.Gender;
                }

                StringBuilder builder = new StringBuilder();
                builder.AppendLine(string.Format("{0} {1} {2} {3} {4} {5}",Title, FirstName, LastName, Email, PhoneNumber, Gender));
                File.AppendAllText("Personal.text", builder.ToString());
                MessageBox.Show("Save", "Information");
                

                }
           

        }

        private void PopulateDropDown()
        {
            Titles.Add(new _Title { Title = "Mr" });
            Titles.Add(new _Title { Title = "Dr" });
            Titles.Add(new _Title { Title = "Miss" });
            Titles.Add(new _Title { Title = "Ms" });
            Titles.Add(new _Title { Title = "Sir" });

            Genders.Add(new _Gender { Gender = "Male" });
            Genders.Add(new _Gender { Gender = "Female" });
        }

        #endregion

        #region RelayCommands

        private RelayCommand _saveCommand = null;
        public RelayCommand SaveCommand
        {
            get
            {
                return _saveCommand = _saveCommand ?? new RelayCommand(() => SaveDetails());
            }
        }

        private RelayCommand _cancelCommand = null;
        public RelayCommand CancelCommand
        {
            get
            {
                return _cancelCommand = _cancelCommand ?? new RelayCommand(() =>  CloseWindow());
            }
        }
        #endregion
    }
}


Second View

<Window x:Class="PhoneBook.View.AddEditView"
        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:PhoneBook.View"
        mc:Ignorable="d"
        Title="AddEditView" Height="300" Width="300">
    <Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="/PhoneBook;component/Resource/Resource.xaml"></ResourceDictionary>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Window.Resources>
    <Grid>
        <Border BorderBrush="Black" BorderThickness="5" Background="AntiqueWhite">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition Height="*"/>
                    <RowDefinition Height="*"/>
                    <RowDefinition Height="*"/>
                    <RowDefinition Height="*"/>
                    <RowDefinition Height="*"/>
                    <RowDefinition Height="*"/>
                    <RowDefinition Height="*"/>
                    <RowDefinition Height="*"/>
                </Grid.RowDefinitions>
                <Label Content="Title"></Label>
                <ComboBox Grid.Row="0"
                          Grid.Column="0"
                          Text="{Binding Title, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
                          ItemsSource="{Binding Titles, UpdateSourceTrigger=PropertyChanged}"
                          SelectedItem="{Binding SelectedTitle, UpdateSourceTrigger=PropertyChanged}"
                          DisplayMemberPath="Title"
                          Margin="3" 
                          Width="100"
                          Height="25"/>
                <Label Grid.Row="1"  
                       Content="First name" 
                       VerticalAlignment="Center" />
                <TextBox Grid.Row="1" 
                         Width="100" 
                         Height="25" 
                         Text="{Binding FirstName}"/>
                <Label Grid.Row="2" 
                       Content="Last name" 
                       VerticalAlignment="Center" />
                <TextBox Grid.Row="2" 
                         Width="100" 
                         Height="25" 
                         Text="{Binding LastName}"/>
                <Label Grid.Row="3" 
                       Content="Email" 
                       VerticalAlignment="Center" />
                <TextBox Grid.Row="3"
                         Text="{Binding Email}"
                         Width="100" 
                         Height="25"/>
                <Label Grid.Row="4"
                       Content="Phone number" 
                       VerticalAlignment="Center" />
                <TextBox Grid.Row="4" 
                         Width="100" 
                         Height="25"
                         Text="{Binding PhoneNumber}"/>
                <Label Grid.Row="5" 
                       Content="Gender"></Label>
                <ComboBox Grid.Row="5"
                          Width="100" 
                          Height="25" 
                          Text="{Binding Gender, Mode=OneWay, NotifyOnTargetUpdated=True}"
                          ItemsSource="{Binding Genders}"
                          DisplayMemberPath="Gender"
                          SelectedItem="{Binding SelectedGender}"/>

                <Button Grid.Row="7"
                        Height="25" 
                        Width="75" 
                        Margin="100,0,0,0" 
                        Content="Cancel" 
                        Command="{Binding CancelCommand}"/>

                <Button 
                    Grid.Row="7" 
                    Height="25"
                    Width="75" 
                    Margin="0,0,100,0" 
                    Content="Save" 
                    Command="{Binding SaveCommand}"/>
            </Grid>
        </Border>
    </Grid>
</Window>
Posted
Updated 11-Sep-17 23:27pm
v2
Comments
Graeme_Grant 12-Sep-17 5:00am    
Duplicate of previous question with slightly different title: How to delete seleted item from a listbox using MVVM.[^]

1 solution

I covered that in my last answer, use an ObservableCollection, not a List<T>. Here: How to delete seleted item from a listbox using MVVM.[^]
 
Share this answer
 
Comments
Stanley Mabunda 12-Sep-17 5:37am    
Its still not working even when I changed to ObservableCollection
Graeme_Grant 12-Sep-17 5:43am    
"Its still not working" tells me nothing. I'm a WPF programmer and use it all the time. It works fine IF implemented correctly. NEVER re-new the collection as it will break the binding and stop working, ALWAYS use .Clear() instead.

Time for you to do some debugging.
Stanley Mabunda 12-Sep-17 5:48am    
I am doing some Debugging. I think the problem is with the Delete Method and Save Method When I Debug I see that is raising property change but ListBox is not updating whenever I have deleted something or added something. My Data is stored and retrieved from a textfile. Or maybe it has to do With the structure of my textfile ?
Graeme_Grant 12-Sep-17 5:56am    
If you peek at the ObservableCollection definition, you can see that it is wired up for binding:
namespace System.Collections.ObjectModel
{
    public class ObservableCollection<T> : Collection<T>, INotifyCollectionChanged, INotifyPropertyChanged
    {
        public event NotifyCollectionChangedEventHandler CollectionChanged;
        protected event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs e);
        protected virtual void OnPropertyChanged(PropertyChangedEventArgs e);
    }
}

But the List definition is not:
namespace System.Collections.Generic
{
    public class List<T> : IList<T>, ICollection<T>, IList, ICollection, IReadOnlyList<T>, IReadOnlyCollection<T>, IEnumerable<T>, IEnumerable
    {
    }
}
Stanley Mabunda 12-Sep-17 6:07am    
Ooooh I see that.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900