I am trying to deleted selected item from a listbox which gets its data from a textfile but I can not feed my Delete method with the right excution to accomplish the task. I I have highted my code in red
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using PhoneBook.View;
using System.Collections.Generic;
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 List _listBox = null;
public List ListBox
{
get
{
return _listBox = _listBox ?? new List();
}
set
{
if (_listBox == value)
{
return;
}
RaisePropertyChanged(MyListPropertyName);
_listBox = value;
RaisePropertyChanged(MyListPropertyName);
}
}
private string _selectedItem = null;
public string SelectedItem
{
get
{
return _selectedItem;
}
set
{
if (_selectedItem != null)
{
return;
}
_selectedItem = value;
RaisePropertyChanged();
}
}
#endregion
#region Method
private void DeleteSelectedItemListBox()
{
string FileName = (@"C: \Users\StanleyM\Desktop\PhoneBook\PhoneBook\bin\Debug\Personal.text");
StreamReader streamReader = new StreamReader(FileName);
string line = "";
int Counter = -1;
while ((line = streamReader.ReadLine()) != null)
{
foreach (var item in line)
{
if (item.ToString() == SelectedItem.ToString())
{
Counter--;
ListBox.Remove(line);
}
}
}
}
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++;
ListBox.Add(item: line);
}
}
private void PopUpWindow()
{
AddEditView PopUp = new AddEditView();
PopUp.ShowDialog();
}
The below is my view
#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
}
}
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">
ItemsSource="{Binding ListBox, UpdateSourceTrigger=PropertyChanged}"
Grid.Row="1">
1 Reply
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Rajeesh MenothPosted Sep 8, 2017, 9:22 AM