0

我一直在阅读如何将 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”,并且未选中单选按钮。

我确信没有其他代码部分正在访问该设置,那么导致这种行为的原因可能是什么?

4

1 回答 1

0

我相信所描述行为的原因是页面在关闭后永远不会被垃圾收集。因此,如果页面的多个实例通过 Bindings 访问 Settings.Default,就会出现问题。我的工作解决方案是在Page_Unloaded事件中进行一些手动“垃圾收集”:

private void Page_Unloaded(object sender, RoutedEventArgs e)
    {
        //stop anything that might keep the page alive
        Settings.Default.PropertyChanged -= Default_PropertyChanged;
        someDispatcherTimer.Stop(); 

        //clear the checkbox bindings to keep the binding working when the page is loaded again
        UiHelper.FindVisualChildren<RadioButton>(settingsTabControl).ToList().ForEach(rb => BindingOperations.ClearBinding(rb, RadioButton.IsCheckedProperty));
    }

请注意,UiHelper.FindVisualChildren()返回在我的页面上具有绑定的所有单选按钮的列表。

于 2018-03-09T15:21:20.310 回答