WPF:绑定RadioButton' IsChecked'到Settings.Default始终设置为' false'

时间:2018-03-07 12:44:59

标签: wpf binding settings ischecked

我一直在阅读如何绑定' IsChecked' RadioButton的属性设置为Settings.Default中的布尔值设置(全部在XAML中)。现在我想要实现的是,每当一个单选按钮被清除时,相应的设置就会被更新并保存。我的代码如下所示:

访问App.xaml中的应用程序设置的全局资源:

xmlns:properties="clr-namespace:MyApp.Properties"

<Application.Resources>
     <ResourceDictionary>
          <properties:Settings x:Key="Settings" />
     </ResourceDictionary>
</Application.Resources>

然后我有一个设置页面,其中有2个RadioButtons用于布尔设置&#39; IsShortProgramFlow&#39; (&#34; On&#34;和&#34; Off&#34;)。

radiobuttons声明如下:

<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>

正如你所看到的,第一个radiobutton没有绑定,因为它会使事情变得更糟。此外,我确信绑定路径是正确的,因此可以正确访问设置。

在我的代码隐藏中,我注册了&#39; Settings.Default.PropertyChanged&#39;实现自动保存功能。 页面的构造函数:

 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();
    }

现在问题是:设置始终设置为“假”&#39;页面打开后,立即关闭并再次打开。因此,当设置设置为&#39; true&#39;然后我打开页面,检查radiobutton应该是什么。但是当我关闭页面并再次打开它(通过框架导航)时,设置会以某种方式设置为&#34; false&#34;没有任何用户交互,也没有检查无线电按钮。

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

1 个答案:

答案 0 :(得分:0)

我认为所描述行为的原因是页面在关闭后永远不会被垃圾收集。因此,如果页面的多个实例通过Bindings访问Settings.Default,则会出现问题。 我的工作解决方案是做一些手动&#34;垃圾收集&#34;在 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()会在我的页面上返回所有带有绑定的radiobuttons列表。