0

So I'm trying to accomplish something like this: For example the standard news app in windows 10 I can select an item: enter image description here

So when I restart the app the selection will still be the same: enter image description here

So I want to accomplish the same thing and even save the selected item as a string. So I probably need 2 localsettings one for the selecteditem and one for saving the content of the selected item as string.

This is what I came up with but this doesn't work (XAML):

<ComboBox Name="Preference" SelectionChanged="ComboBox_SelectionChanged">
    <ComboBoxItem Content="Diving"/>
    <ComboBoxItem Content="Snorkeling"/>
    <ComboBoxItem Content="Diving and Snorkeling"/>
</ComboBox>

(cs)

public Settings()
{
    this.InitializeComponent();

    Preference.SelectedItem = App.localSettings.Values["Preference"];
}

private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    App.localSettings.Values["Preference"] = Preference.SelectedItem;
}

I'm still trying to learn C# so please keep it simple. I tried searching it but didn't really find something to answer my questions.

Red fx
  • 1,071
  • 2
  • 12
  • 26
user6480540
  • 74
  • 1
  • 10
  • Check https://stackoverflow.com/questions/845030/bind-to-a-value-defined-in-the-settings to bind properties directly to settings. – Fruchtzwerg Sep 19 '17 at 13:01
  • and one more another type of way . you can save it to storage in a txt file so each time when app launch or initialize any page that txt file from storage automatically set it to last save state – Shubham Sahu Sep 19 '17 at 15:12

1 Answers1

2

The SelectedItem needs to be an actual item that the ComboBox contains. You're populating the ComboBox with ComboBoxItems, so your SelectedItem needs to be a ComboBoxItem.

There are two ways you can solve this. The first is to set the SelectedItem to be the CombobBoxItem that has the same Content as your string. The second is to populate the ComboBox with strings instead.

One (Code only change)

string preference = PreferenceApp.localSettings.Values["Preference"];
Preference.SelectedItem = Preference.Items.OfType<ComboBoxItem>().FirstOrDefault(item => item.Content == preference);

Two (XAML only change)

<ComboBox Name="Preference" SelectionChanged="ComboBox_SelectionChanged">
    <x:String>Diving</x:String>
    <x:String>Snorkeling</x:String>
    <x:String>Diving and Snorkeling</x:String>
</ComboBox>
Shawn Kendrot
  • 12,425
  • 1
  • 25
  • 41