Here is a working example for you...
1.
MainWindow
XAML:
<Window x:Class="WpfSaveSelectedItemToSettings.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:WpfSaveSelectedItemToSettings"
mc:Ignorable="d" x:Name="Window"
Title="MainWindow" Height="450" Width="800"
Closing="MainWindow_OnClosing">
<Grid DataContext="{Binding ElementName=Window}"
HorizontalAlignment="Center"
VerticalAlignment="Center">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<ComboBox x:Name="AudioDeviceList"
ItemsSource="{Binding AudioDevices}"
SelectedItem="{Binding SelectedItem}"
SelectedIndex="{Binding SelectedIndex}"
Width="400"
Margin="0 10"/>
<TextBlock DataContext="{Binding ElementName=AudioDeviceList}"
Grid.Row="1">
<Run Text="Selected Item: " FontWeight="Bold"/>
<Run Text="{Binding SelectedItem}"></Run>
</TextBlock>
</Grid>
</Window>
2.
MainWindow
Code Behind (part 1 - core code):
public partial class MainWindow : Window, INotifyPropertyChanged
{
public MainWindow()
{
InitializeComponent();
InitData();
LoadSelected();
}
private int selectedIndex = -1;
private const string DeviceKey = "SelectedDevice";
private readonly Random random = new Random();
public ObservableCollection<string> AudioDevices { get; } = new();
public string SelectedItem { get; set; }
public int SelectedIndex
{
get => selectedIndex;
set => SetField(ref selectedIndex, value);
}
private void InitData()
{
List<string> discoveredDevices = new()
{
"Logitech G533 Wireless Gaming Headset",
"HyperX Cloud II Gaming Headset",
"Creative Sound BlasterX G5 Portable USB DAC",
"SteelSeries Arctis 7 Wireless Gaming Headset",
"Razer Nari Ultimate Wireless Gaming Headset",
"Astro A50 Wireless Gaming Headset",
"Bose QuietComfort 35 II Wireless Headphones",
"Plantronics RIG 800LX Wireless Gaming Headset",
"JBL Quantum 800 Wireless Gaming Headset",
"Corsair Virtuoso RGB Wireless SE Gaming Headset",
};
discoveredDevices = discoveredDevices.OrderBy(
x => Guid.NewGuid()).ToList();
int maxDiscovered = random.Next(3, discoveredDevices.Count);
for (int i = 0; i < maxDiscovered; i++)
AudioDevices.Add(discoveredDevices[i]);
}
private void MainWindow_OnClosing(object? sender, CancelEventArgs e)
=> SaveSelected();
private void LoadSelected()
{
string? selectedDevice = LoadAppSetting(DeviceKey);
if (string.IsNullOrWhiteSpace(selectedDevice))
return;
SelectedIndex = AudioDevices.IndexOf(selectedDevice);
}
private void SaveSelected()
{
if (string.IsNullOrWhiteSpace(SelectedItem))
return;
SaveAppSetting(DeviceKey, SelectedItem);
}
Above we have the implementation for managing the selected ComboBox item from saved data.
If you want to save on selection, not on closing of the app, then unhook the
MainWindow_OnClosing
event and update the
SelectedIndex
property with the following:
public int SelectedIndex
{
get => selectedIndex;
set
{
SetField(ref selectedIndex, value);
SaveSelected();
}
}
3.
MainWindow
Code Behind (part 2 - support code):
#region App.Config Load/Save Implementation
private string? LoadAppSetting(string key)
{
Configuration configFile = LoadConfiguration();
KeyValueConfigurationCollection? appSettings =
configFile.AppSettings.Settings;
if (appSettings is null)
return default;
return appSettings[key].Value;
}
private void SaveAppSetting(string key, string value)
{
try
{
Configuration configFile = LoadConfiguration();
KeyValueConfigurationCollection? settings =
configFile.AppSettings.Settings;
if (settings[key] == null)
settings.Add(key, value);
else
settings[key].Value = value;
configFile.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection(
configFile.AppSettings.SectionInformation.Name);
}
catch (ConfigurationErrorsException)
{
Console.WriteLine("Error saving settings!");
}
}
private static Configuration LoadConfiguration()
{
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename =
AppDomain.CurrentDomain.BaseDirectory +
"..\\..\\App.Config";
Configuration configFile = ConfigurationManager
.OpenMappedExeConfiguration(fileMap,
ConfigurationUserLevel.None);
return configFile;
}
#endregion
#region INotifyPropertyChanged Implementation
public event PropertyChangedEventHandler? PropertyChanged;
protected virtual void OnPropertyChanged(
[CallerMemberName] string? propertyName = null)
{
PropertyChanged?.Invoke(this,
new PropertyChangedEventArgs(propertyName));
}
protected bool SetField<T>(ref T field, T value,
[CallerMemberName] string? propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(field, value))
return false;
field = value;
OnPropertyChanged(propertyName);
return true;
}
#endregion
}
This part shows how to load/save from the
App.Config
file. Also the support for Data Binding.
Enjoy!