How do i get back a listbox item after a window closes in C# WPF

Sahana M 1 Reputation point
2020-04-22T06:02:19.737+00:00

I have 1 Listbox it takes items from TextBox, when an item is added to the listbox and the application is closed, upon opening the application the item added to the listbox will still be present.

Use case:

User opens application.
User adds item called "Item 1" to listbox using button.
User closes application.
User opens application again and sees that "Item 1" is still in the listbox, and the added item hasn't been lost by the application closing.

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,663 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Peter Fleischer (former MVP) 19,231 Reputation points
    2020-04-22T15:29:43.187+00:00

    Hi, try following demo. At first you must select typ of buffer to store items (lines). In demo I use ObservableCollection and txt file for saving items. In constructor I load the items (lines) and in destructor I save items (lines).

    XAML:

    <Window x:Class="Window010"
            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:WpfApp1.WpfApp010"
            mc:Ignorable="d"
            Title="Window010" Height="450" Width="800">
      <Window.DataContext>
        <local:ViewModel/>
      </Window.DataContext>
        <StackPanel>
        <TextBox Text="{Binding Text}" Margin="5"/>
        <Button Content="Add Item" Command="{Binding Cmd}" Margin="5"/>
        <ListBox ItemsSource="{Binding Col}" Margin="5"/>
      </StackPanel>
    </Window>
    

    Code:

    Imports System.Collections.ObjectModel
    Imports System.ComponentModel
    Imports System.IO
    Imports System.Runtime.CompilerServices
    
    Namespace WpfApp010
      Public Class ViewModel
        Implements IDisposable
    
        Private filePath As String = "c:\temp\xTest.txt"
        Public Sub New()
          If File.Exists(filePath) Then
            Col = New ObservableCollection(Of String)(File.ReadAllLines(filePath))
          Else
            Col = New ObservableCollection(Of String)
          End If
        End Sub
    
        Public Property Text As String
        Public Property Col As ObservableCollection(Of String)
        Public ReadOnly Property Cmd As ICommand = New RelayCommand(Sub(state)
                                                                      Col.Add(Text)
                                                                    End Sub)
    
    #Region "IDisposable Support"
        Private disposedValue As Boolean 
        Protected Overridable Sub Dispose(disposing As Boolean)
          If Not disposedValue Then
            File.WriteAllLines(filePath, Col.ToArray)
          End If
          disposedValue = True
        End Sub
        Protected Overrides Sub Finalize()
          Dispose(False)
          MyBase.Finalize()
        End Sub
        Public Sub Dispose() Implements IDisposable.Dispose
          Dispose(True)
        End Sub
    #End Region
      End Class
    
      Public Class RelayCommand
        Implements ICommand
        Private ReadOnly _execute As Action(Of Object)
        Public Sub New(ByVal execute As Action(Of Object))
          Me._execute = execute
        End Sub
        Public Function CanExecute(ByVal parameter As Object) As Boolean Implements ICommand.CanExecute
          Return True
        End Function
        Public Custom Event CanExecuteChanged As EventHandler Implements ICommand.CanExecuteChanged
          AddHandler(ByVal value As EventHandler)
            AddHandler CommandManager.RequerySuggested, value
          End AddHandler
          RemoveHandler(ByVal value As EventHandler)
            RemoveHandler CommandManager.RequerySuggested, value
          End RemoveHandler
          RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
          End RaiseEvent
        End Event
        Public Sub Execute(ByVal parameter As Object) Implements ICommand.Execute
          Me._execute(parameter)
        End Sub
      End Class
    End Namespace
    

    ViewModel in CSharp:

    using System;
    using System.Collections.ObjectModel;
    using System.IO;
    using System.Linq;
    using System.Windows;
    using System.Windows.Input;
    
    namespace WpfApp1
    {
      namespace WpfApp010
      {
        public class ViewModel : IDisposable
        {
          private string filePath = @"c:\temp\xTest.txt";
    
          public ViewModel()
          {
            if (File.Exists(filePath)) Col = new ObservableCollection<String>(File.ReadAllLines(filePath));
            else Col = new ObservableCollection<String>();
          }
    
          public string Text { get; set; }
          public ObservableCollection<string> Col { get; set; }
          public ICommand Cmd { get => new RelayCommand((state) => Col.Add(Text)); }
    
          #region IDisposable Support
          private bool disposedValue;
          protected void Dispose(bool disposing)
          {
            if (!disposedValue) File.WriteAllLines(filePath, Col.ToArray());
            disposedValue = true;
          }
          ~ViewModel() => Dispose(false);
          public void Dispose() => Dispose(true);
          #endregion
        }
        public class RelayCommand : ICommand
        {
          private readonly Predicate<object> _canExecute;
          private readonly Action<object> _action;
          public RelayCommand(Action<object> action) : this(action, null) { }
          public RelayCommand(Action<object> action, Predicate<object> canExecute) { _action = action; _canExecute = canExecute; }
          public void Execute(object o) => _action(o);
          public bool CanExecute(object o) => _canExecute == null ? true : _canExecute(o);
          public event EventHandler CanExecuteChanged
          {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
          }
        }
      }
    }
    
    0 comments No comments

  2. Alex Li-MSFT 1,096 Reputation points
    2020-04-23T02:30:09.983+00:00

    Welcome to our Microsoft Q&A platform!

    You can use ini file to remember ListBox Information:

     public partial class MainWindow : Window  
        {  
            [DllImport("kernel32")]  
            private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);  
            [DllImport("kernel32")]  
            private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);  
            string iniFilePath = System.Environment.CurrentDirectory + @"\config.ini";  
            string iniHead = "ListBoxInformation";  
            string iniKey = "Key";  
            string iniValue;  
            StringBuilder temp;  
            public MainWindow()  
            {  
                InitializeComponent();  
            }  
      
            private void Button_Click(object sender, RoutedEventArgs e)  
            {  
                if (iniValue == null)  
                {  
                    iniValue += temp;  
                }  
                string str = textBox1.Text;  
                if (!string.IsNullOrEmpty(str))  
                {  
                    iniValue =  iniValue+","+str;  
                    listBox1.Items.Add(textBox1.Text);  
                    WritePrivateProfileString(iniHead, iniKey, iniValue, iniFilePath);                
                }  
            }  
      
            private void Window_Loaded(object sender, RoutedEventArgs e)  
            {  
                temp = new StringBuilder(1024);  
                GetPrivateProfileString(iniHead, iniKey, "", temp, 1024, iniFilePath);  
                foreach (var item in temp.ToString().Split(new char[] { ',' }))  
                {  
                    if(! string.IsNullOrEmpty(item))  
                    listBox1.Items.Add(item);  
                }  
            }  
        }  
    

    7616-annotation-2020-04-23-102727.png

    7595-1.gif

    Thanks.