Quick WPF Tip: How to bind to WPF application resources and settings?

You, probable know, that you can save application resources and settings within handy classes Settings and Properties, provided by Visual Studio code generator. Just put your values, set the usage scope and all you have to do is to save it upon request.

image

This feature is really useful and great time saver. But how to use it from WPF? Visual Studio do not know to create Dependency Objects for setting and resource… Following the sample of how designer saves setting information

[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
   [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "9.0.0.0")]
   internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
       private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
       public static Settings Default {
           get {
               return defaultInstance;
           }
       }
       [global::System.Configuration.UserScopedSettingAttribute()]
       [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
       [global::System.Configuration.DefaultSettingValueAttribute("0")]
       public double Left {
           get {
               return ((double)(this["Left"]));
           }
           set {
               this["Left"] = value;
           }
       }

As you can see it creates singleton and publish relevant properties through it, thus you can access the information by using following syntax

UserSettings.Properties.Settings.Default.Left = 10;

But how to create binding for such structure? Simple – this is regular static class. As well as DateTime.Now and so. Also we are not interested to know, whenever this property updated. This means, that following code will do all necessary work.

<Window x:Class="UserSettings.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:p="clr-namespace:UserSettings.Properties"
    WindowStartupLocation="Manual"
    Title="Window1"
    Height="{Binding Source={x:Static p:Settings.Default}, Path=Height, Mode=TwoWay}"
    Width="{Binding Source={x:Static p:Settings.Default}, Path=Width, Mode=TwoWay}"
    Left="{Binding Source={x:Static p:Settings.Default}, Path=Left, Mode=TwoWay}"
    Top="{Binding Source={x:Static p:Settings.Default}, Path=Top, Mode=TwoWay}"

As you see, we just point by using x:Static provider of type UserSettings.Properties.Settings.Default and requesting it’s members. Now all you have to do is to save updated information upon the application exit.

protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            Settings.Default.Save();
            base.OnClosing(e);
        }

We done. Starting now, user can move and resize WPF window and all information will be saved in Settings class automatically. Next time this user will open the application it will restore it state (position and size) automatically.

Happy coding.

  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DotNetKicks
  • DZone
  • Live
  • Reddit
  • TwitThis
  • email
  • Slashdot
  • StumbleUpon

You may also be interested with:

  1. Real singleton approach in WPF application
  2. INotifyPropertyChanged auto wiring or how to get rid of redundant code

5 Responses to “Quick WPF Tip: How to bind to WPF application resources and settings?”

  1. tom103 Says:

    This syntax for binding to settings is quite awkward, so I wrote the following class :

    —————————————————–

       public class SettingBindingExtension : Binding

       {

           public SettingBindingExtension()

           {

               Initialize();

           }

           public SettingBindingExtension(string path)

               :base(path)

           {

               Initialize();

           }

           private void Initialize()

           {

               this.Source = Properties.Settings.Default;

               this.Mode = BindingMode.TwoWay;

           }

       }

    —————————————————–

    You can use it like this :

    —————————————————–

    <Window x:Class="UserSettings.Window1"

       xmlns="schemas.microsoft.com/…/presentation"

       xmlns:x="schemas.microsoft.com/…/xaml"

       xmlns:my="clr-namespace:WpfApplication1"

       WindowStartupLocation="Manual"

       Title="Window1"

       Height="{SettingBinding Height}"

       Width="{SettingBinding Width}"

       Left="{SettingBinding Left}"

       Top="{SettingBinding Top}">

    —————————————————–

  2. WPF Certification Study Guide « Project Files Says:

    Pingback from  WPF Certification Study Guide &laquo; Project Files

  3. Tamir Khason Says:

    Andrew, this is only sample how to do it. It is not final implementation. However this is the way how to use application settings and resources by using WPF binding

  4. Andrew Says:

    This is a great example of how to bind to settings, but unfortunately it is far from the best way to save and restore your window placement.

    msdn2.microsoft.com/…/aa972163.aspx

  5. Joe Says:

    Great stuff.

    On saving the app location – you might want to do a multi-binding with the Screen resolution just in case the user switches from a multi-monitor set-up to a single monitor and the app sits off the screen somewhere.

Leave a Reply

Recommended

 


Sponsor


Partners

WPF Disciples
Dreamhost
Code Project
Switched to Better Place

Together