UWP - 保存设置不能一直工作

时间:2017-09-06 12:36:35

标签: xaml uwp settings c++-cx

我从here复制了以下代码。我想将一个double值绑定到一个xaml滑块,每次导航到SettingsPage时都会从localsetting中获取此值,并且每次使用者更改slidervalue时我希望将它保存到localsettings。到目前为止,这是我的代码:

SettingsPage.xaml.cpp:

Windows::Storage::ApplicationDataContainer^ localSettings = Windows::Storage::ApplicationData::Current->LocalSettings;


SettingsPage::SettingsPage()
{
    InitializeComponent();

    this->viewModel = ref new SettingsViewModel();
    this->DataContext = this->viewModel;
}

void SettingsPage::QSlider_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e)
{
    Windows::Storage::ApplicationDataCompositeValue^ composite =ref new Windows::Storage::ApplicationDataCompositeValue();
    bool a  = composite->Insert(SETTINGS_TAG_SLIDER_Q, dynamic_cast<PropertyValue^>(PropertyValue::CreateDouble((double)sldQ->Value)));

    auto values = localSettings->Values;
    bool b  = values->Insert(SETTINGS_TAG_SETTINGS_PAGE, composite);
}

SettingsPage.xaml:

<Slider x:Name="sldQ" Margin="15,5,15,0" Value="{Binding SliderQValue}" ValueChanged="Slider_ValueChanged" MaxWidth="300" HorizontalContentAlignment="Left" ></Slider>

SettingsViewModel.cpp:

double SettingsViewModel::SliderQValue::get()
{
    Windows::Storage::ApplicationDataContainer^ localSettings = Windows::Storage::ApplicationData::Current->LocalSettings;
    ApplicationDataCompositeValue^ composite = safe_cast<ApplicationDataCompositeValue^>(localSettings->Values->Lookup(SETTINGS_TAG_SETTINGS_PAGE));
    if (composite != nullptr)
    {
        if (composite->HasKey(SETTINGS_TAG_SLIDER_Q)) {
            double value = safe_cast<IPropertyValue^>(composite->Lookup(SETTINGS_TAG_SLIDER_Q))->GetDouble();
            return value;
        }
    }
    return 99;
}

我的问题是,这只适用一次!如果我从其他页面导航到SettingsPage,我得到slidervalue = 99。然后我通过拖动来设置它,例如然后我导航回到其他页面。从另一页面我再次导航到SettingsPage并获得slidervalue = 50。但再次这样做我又得到了99。所以它只适用于1页导航周期,但即使应用程序重新启动它也应该有效。我的代码有什么问题?我理解错了吗?

1 个答案:

答案 0 :(得分:1)

我实际上是在this的帮助下解决了这个问题。在上面的代码中,每次我想写/读它时,我都在初始化一个新的'ApplicationDateCompositeValue'。因此,使用新方法,它的工作方式与预计的相同:

OnValueChanged:

Windows::Storage::ApplicationDataContainer^ localSettings = Windows::Storage::ApplicationData::Current->LocalSettings;
    auto values = localSettings->Values;
    values->Insert(TAG_SLIDER, dynamic_cast<PropertyValue^>(PropertyValue::CreateDouble((double)sldQuality->Value)));

属性::得到():

ApplicationDataContainer^ localSettings = ApplicationData::Current->LocalSettings;
    auto values = localSettings->Values;
    if (localSettings->Values->HasKey(TAG_SLIDER)) {
        double value = safe_cast<double>(localSettings->Values->Lookup(TAG_SLIDER));
        return value;
    }
    else
        return default_value;