I try to reproduce the problem environment and rewrite the OnClosing
method. It can work. You could check it out.
Here's saving the SelectedItem to a setting file.
<Window x:Class="SelectedItemSave.MainWindow"
...
xmlns:local="clr-namespace:SelectedItemSave"
xmlns:p="clr-namespace:SelectedItemSave.Properties"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<StackPanel>
<Button x:Name="btn" Click="btn_Click" Height="30" Content=" add item"/>
<ComboBox Name="cmb1" Height="50" ItemsSource="{Binding Icv}" DisplayMemberPath="Name"
SelectedValue="{Binding Source={x:Static p:Settings.Default}, Path=p, Mode=TwoWay}" SelectedValuePath="Id"/>
</StackPanel>
</Grid>
</Window>
Codebehind:
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Data;
namespace ComboBoxSaveSelectedItem
{
public partial class MainWindow : Window, INotifyPropertyChanged
{
public int flag = 2;
public MainWindow()
{
InitializeComponent();
DataContext = this;
if (flag != null)
{
string sIdDefaultRender = null;
devices.Add(new AudioDevice() { Name = "System default", Direction = "Playback", Id = sIdDefaultRender, Default = true });
devices.Insert(devices.Count - 0, new AudioDevice() { Name = "Selected application ...", Direction = "Recording", Id = "Idlast", Default = false });
Icv = new ListCollectionView(devices);
Icv.GroupDescriptions.Add(new PropertyGroupDescription("Direction"));
this.cmb1.ItemsSource = Icv;
}
DataContext = this;
}
private ObservableCollection<AudioDevice> devices = new ObservableCollection<AudioDevice>();
public ObservableCollection<AudioDevice> Devices
{
get { return devices; }
set
{
if (devices != value)
{
devices = value;
OnPropertyChanged("Devices");
}
}
}
private AudioDevice selectedItem;
public AudioDevice SelectedItem
{
get { return selectedItem; }
set
{
selectedItem = value;
OnPropertyChanged("SelectedItem");
}
}
private ICollectionView icv;
public ICollectionView Icv
{
get { return icv; }
set
{
icv = value;
OnPropertyChanged("Icv");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string name = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
Properties.Settings.Default.Save();
base.OnClosing(e);
}
}
public class AudioDevice
{
public string Id { get; set; }
public string Name { get; set; }
public string Direction { get; set; }
public bool Default { get; set; }
public AudioDevice() { }
}
}
The result:
-
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our [documentation][5] to enable e-mail notifications if you want to receive the related email notification for this thread.