在本地设置中保存组合框选择,以便在应用启动时检索此

时间:2017-09-19 12:56:02

标签: c# combobox uwp

所以我试图完成这样的事情: 例如,Windows 10中的标准新闻应用程序我可以选择一个项目: enter image description here

因此,当我重新启动应用程序时,选择仍然是相同的: enter image description here

所以我想完成同样的事情,甚至将所选项目保存为字符串。所以我可能需要2个本地设置一个用于选定项目,一个用于将所选项目的内容保存为字符串。

这是我提出的,但这不起作用(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;
}

我还在尝试学习C#所以请保持简单。我尝试过搜索它,但没有真正找到回答我问题的东西。

1 个答案:

答案 0 :(得分:2)

SelectedItem需要是ComboBox包含的实际项目。您正在使用ComboBoxItems填充ComboBox,因此您的SelectedItem需要是ComboBoxItem。

有两种方法可以解决这个问题。第一种方法是将SelectedItem设置为与字符串具有相同内容的CombobBoxItem。第二种是用字符串填充ComboBox。

一个(仅限代码更改)

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

两个(仅限XAML更改)

<ComboBox Name="Preference" SelectionChanged="ComboBox_SelectionChanged">
    <x:String>Diving</x:String>
    <x:String>Snorkeling</x:String>
    <x:String>Diving and Snorkeling</x:String>
</ComboBox>