【问题标题】:Save combobox selection in localsettings to retrieve this at startup of the app在本地设置中保存组合框选择以在应用程序启动时检索它
【发布时间】:2018-02-28 06:39:12
【问题描述】:

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

所以当我重新启动应用程序时,选择仍然是相同的:

所以我想完成同样的事情,甚至将所选项目保存为字符串。所以我可能需要 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#,所以请保持简单。我尝试搜索它,但并没有真正找到可以回答我的问题的东西。

【问题讨论】:

  • 选中stackoverflow.com/questions/845030/… 将属性直接绑定到设置。
  • 还有另一种方式。您可以将其保存到 txt 文件的存储中,因此每次应用启动或初始化任何页面时,存储中的 txt 文件都会自动将其设置为上次保存状态

标签: c# combobox uwp


【解决方案1】:

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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-19
    • 1970-01-01
    • 1970-01-01
    • 2018-03-17
    • 1970-01-01
    • 2014-03-22
    • 1970-01-01
    相关资源
    最近更新 更多