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