如何在 UWP 中保存组合框的选定索引并在用户重新加载页面时将其显示回来?

How to save selected index of a combobox in UWP and display it back when the user reloads the page?

我的 UWP 应用程序中有一个 ComboBox 控件,当用户选择一个选项时,我需要保存它的选定索引!然后,我需要将这个索引保存在本地设置中,当用户返回此页面时,我希望 ComboBox 将这个保存的索引作为选定的索引。我的设置页面需要这个功能!谁能帮我?

这是我的代码:

private void fuelTypeSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    var localSettings = ApplicationData.Current.LocalSettings;

    try
    {
        if(localSettings.Values.ContainsKey("selectedIndex"))
        {
            int index = (int)localSettings.Values["selectedIndex"];
            fuelTypeSelector.SelectedIndex = index;

            //update the saved index

            if(fuelTypeSelector.SelectedIndex!=index)
            {
                localSettings.Values["selectedIndex"] =
                    fuelTypeSelector.SelectedIndex;
            }
        }
        else
        {
            // index does not exist
            localSettings.Values.Add("selectedIndex",
                fuelTypeSelector.SelectedIndex);
        }
    }
    catch(Exception ex)
    {

    }
}

获取ComboBox, you can handle its SelectionChanged event的选中项,这里举例:

<ComboBox SelectionChanged="ComboBox_SelectionChanged">
    <ComboBoxItem>Item 1</ComboBoxItem>
    <ComboBoxItem>Item 2</ComboBoxItem>
    <ComboBoxItem>Item 3</ComboBoxItem>
    <ComboBoxItem>Item 4</ComboBoxItem>
    <ComboBoxItem>Item 5</ComboBoxItem>
</ComboBox>

隐藏代码:

private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    //you can get the selected item like this:
    var combo = sender as ComboBox;
    var selecteditem = combo.SelectedItem;

    //or, since ComboBox DOESN'T support multiple selection, you can get the item like:
    var selecteditems = e.AddedItems.FirstOrDefault();
}

或者如果你只需要这个项目的索引,你可以使用第一种方法并更改代码如下:var selectedindex = combo.SelectedIndex;。当然我们也可以通过data binding.

ComboBox的Collection添加项目

通过保存选择项,我个人认为最好是在你的应用处于挂起阶段时保存你的本地设置,并在启动阶段读取设置数据。查看UWP app的生命周期,官方文档Launching, resuming, and background tasks will help you. This means you will have to save your page state during the run time of your app, to do this, you can cache your Setting page, for more information about page state, you can refer to my answer in UWP page state manage.

关于保存和检索设置部分,这里是官方文档:Store and retrieve settings and other app data,这个文档中有一些示例代码。

最后,由于您是 UWP 应用程序开发的新手,您可以参考 GitHub 上的 How-to articles for UWP apps on Windows 10 to get started. And there are a lot of official UWP samples,这也可能有所帮助。