C# 在localsettings中保存组合框选择,以便在应用程序启动时检索此选项

C# 在localsettings中保存组合框选择,以便在应用程序启动时检索此选项,c#,combobox,uwp,C#,Combobox,Uwp,因此,我正在努力实现以下目标: 例如,windows 10中的标准新闻应用程序我可以选择一个项目: 因此,当我重新启动应用程序时,选择仍然相同: 因此,我想完成同样的事情,甚至将所选项目保存为字符串。因此,我可能需要两个localsettings,一个用于selecteditem,另一个用于将所选项目的内容保存为字符串 这是我想到的,但这不适用于XAML: <ComboBox Name="Preference" SelectionChanged="ComboBox_SelectionC

因此,我正在努力实现以下目标: 例如,windows 10中的标准新闻应用程序我可以选择一个项目:

因此,当我重新启动应用程序时,选择仍然相同:

因此,我想完成同样的事情,甚至将所选项目保存为字符串。因此,我可能需要两个localsettings,一个用于selecteditem,另一个用于将所选项目的内容保存为字符串

这是我想到的,但这不适用于XAML:

<ComboBox Name="Preference" SelectionChanged="ComboBox_SelectionChanged">
    <ComboBoxItem Content="Diving"/>
    <ComboBoxItem Content="Snorkeling"/>
    <ComboBoxItem Content="Diving and Snorkeling"/>
</ComboBox>
我还在努力学习C,所以请保持简单。我尝试搜索它,但没有真正找到答案。

SelectedItem必须是组合框包含的实际项目。您正在用ComboBoxItems填充ComboBox,因此您的SelectedItem必须是ComboBoxItem

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

只改变一个代码

string preference = PreferenceApp.localSettings.Values["Preference"];
Preference.SelectedItem = Preference.Items.OfType<ComboBoxItem>().FirstOrDefault(item => item.Content == preference);
<ComboBox Name="Preference" SelectionChanged="ComboBox_SelectionChanged">
    <x:String>Diving</x:String>
    <x:String>Snorkeling</x:String>
    <x:String>Diving and Snorkeling</x:String>
</ComboBox>
两个XAML只能更改

string preference = PreferenceApp.localSettings.Values["Preference"];
Preference.SelectedItem = Preference.Items.OfType<ComboBoxItem>().FirstOrDefault(item => item.Content == preference);
<ComboBox Name="Preference" SelectionChanged="ComboBox_SelectionChanged">
    <x:String>Diving</x:String>
    <x:String>Snorkeling</x:String>
    <x:String>Diving and Snorkeling</x:String>
</ComboBox>
SelectedItem必须是组合框包含的实际项。您正在用ComboBoxItems填充ComboBox,因此您的SelectedItem必须是ComboBoxItem

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

只改变一个代码

string preference = PreferenceApp.localSettings.Values["Preference"];
Preference.SelectedItem = Preference.Items.OfType<ComboBoxItem>().FirstOrDefault(item => item.Content == preference);
<ComboBox Name="Preference" SelectionChanged="ComboBox_SelectionChanged">
    <x:String>Diving</x:String>
    <x:String>Snorkeling</x:String>
    <x:String>Diving and Snorkeling</x:String>
</ComboBox>
两个XAML只能更改

string preference = PreferenceApp.localSettings.Values["Preference"];
Preference.SelectedItem = Preference.Items.OfType<ComboBoxItem>().FirstOrDefault(item => item.Content == preference);
<ComboBox Name="Preference" SelectionChanged="ComboBox_SelectionChanged">
    <x:String>Diving</x:String>
    <x:String>Snorkeling</x:String>
    <x:String>Diving and Snorkeling</x:String>
</ComboBox>

选中此项可将属性直接绑定到设置。还有另一种方式。您可以将其保存到txt文件中的存储器中,以便每次应用程序启动或初始化任何页面时,txt文件从存储器中自动将其设置为上次保存状态检查以将属性直接绑定到设置。以及另一种方式。您可以将其保存到txt文件中的存储器中,以便每次应用程序启动或初始化任何页面时,该txt文件从存储器中自动将其设置为上次保存状态