Как сделать так, чтобы мой список обновлялся при нажатии кнопки Удалить ?
У меня есть список, который, когда я выбираю элемент, а затем нажимаю кнопку Удалить, изменения не отображаются сразу, пока я не выхожу из приложения, а затем снова его запускаю. Изменения отражаются только тогда, когда я это сделал. То же самое касается моей кнопки сохранения во втором окне, когда я нажимаю кнопку Сохранить, мой список не обновляет вновь добавленный элемент до тех пор, пока я не выйду из приложения и не вернусь к нему снова, то есть когда я увижу, что я добавил.
Что я уже пробовал:
ViewModel для моего первого 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 } }
Первый Взгляд
<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 для моего второго окна
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 } }
второй взгляд
<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>
Graeme_Grant
Дубликат предыдущего вопроса с немного другим названием: Как удалить выбранный элемент из списка с помощью MVVM.[^]