我一直在阅读如何将 RadioButton 的“IsChecked”属性绑定到 Settings.Default 中的布尔设置(全部在 XAML 中)。现在我想要实现的是,每次检查单选按钮时,相应的设置都会更新并保存。我的代码如下所示:
用于访问 App.xaml 中的应用程序设置的全局资源:
xmlns:properties="clr-namespace:MyApp.Properties"
<Application.Resources>
<ResourceDictionary>
<properties:Settings x:Key="Settings" />
</ResourceDictionary>
</Application.Resources>
然后我有一个带有 2 个单选按钮的设置页面,用于布尔设置“IsShortProgramFlow”(“开”和“关”)。
单选按钮声明如下:
<RadioButton Name="rbShortProgramFlowNo" Content="Off" GroupName="programFlow"> </RadioButton>
<RadioButton Name="rbShortProgramFlowYes" IsChecked="{Binding Source={StaticResource Settings}, Path=Default.IsShortProgramFlow, Mode=TwoWay}" Content="On" GroupName="programFlow"></RadioButton>
如您所见,第一个单选按钮没有绑定,因为它使事情变得更糟。另外,我确信绑定路径是正确的,因此可以正确访问设置。
在我的代码隐藏中,我注册了“Settings.Default.PropertyChanged”来实现自动保存功能。页面构造器:
Settings.Default.PropertyChanged -= Default_PropertyChanged;
Settings.Default.PropertyChanged += Default_PropertyChanged;
方法:
private void Default_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (isInitialisation)
return;
Settings.Default.Save();
}
现在的问题是:一旦打开、关闭并再次打开页面,该设置总是设置为“false”。因此,当设置设置为“true”并且我打开页面时,单选按钮会被选中。但是当我关闭页面并再次打开它(通过框架导航)时,该设置在没有任何用户交互的情况下以某种方式设置为“false”,并且未选中单选按钮。
我确信没有其他代码部分正在访问该设置,那么导致这种行为的原因可能是什么?