我從下面的代碼複製了here。我想將一個double值綁定到一個xaml滑塊,每次我導航到SettingsPage時都會從本地設置中獲取此值,並且每次slidervalue被用戶更改時,我都希望將它保存到localsettings中。這是我到目前爲止的代碼:UWP - 保存設置不會一直工作
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,則滑動值= 99。然後我通過拖動到例如然後我導航回其他頁面。從另一頁我再次導航到SettingsPage並獲得slidervalue = 50。但再次做到這一點,我又得到了99。所以它只適用於1頁導航循環,但即使應用程序重新啓動,它也可以工作。我的代碼中有什麼問題?我是否理解錯誤?