Best way to bind WPF properties to ApplicationSettings in C#?

后端 未结 7 727
野的像风
野的像风 2020-12-07 15:40

What is the best way to bind WPF properties to ApplicationSettings in C#? Is there an automatic way like in a Windows Forms Application? Similar to this question, how (and

7条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-07 16:28

    Kris, I'm not sure this is the best way to bind ApplicationSettings, but this is how I did it in Witty.

    1) Create a dependency property for the setting that you want to bind in the window/page/usercontrol/container. This is case I have an user setting to play sounds.

        public bool PlaySounds
        {
            get { return (bool)GetValue(PlaySoundsProperty); }
            set { SetValue(PlaySoundsProperty, value); }
        }
    
        public static readonly DependencyProperty PlaySoundsProperty =
            DependencyProperty.Register("PlaySounds", typeof(bool), typeof(Options),
            new FrameworkPropertyMetadata(false, new PropertyChangedCallback(OnPlaySoundsChanged)));
    
        private static void OnPlaySoundsChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
        {
            Properties.Settings.Default.PlaySounds = (bool)args.NewValue;
            Properties.Settings.Default.Save();
        }
    

    2) In the constructor, initialize the property value to match the application settings

          PlaySounds = Properties.Settings.Default.PlaySounds;
    

    3) Bind the property in XAML

          
    

    You can download the full Witty source to see it in action or browse just the code for options window.

提交回复
热议问题