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

22 באפריל 2008

4 תגובות

[This blog was migrated. You will not be able to comment here.
The new URL of this post is http://khason.net/blog/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.

הוסף תגובה
facebook linkedin twitter email

כתיבת תגובה

האימייל לא יוצג באתר. (*) שדות חובה מסומנים

4 תגובות

  1. Joe22 באפריל 2008 ב 22:18

    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.

    להגיב
  2. Andrew23 באפריל 2008 ב 6:03

    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.

    http://msdn2.microsoft.com/en-us/library/aa972163.aspx

    להגיב
  3. Tamir Khason23 באפריל 2008 ב 8:46

    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. tom10317 בנובמבר 2008 ב 21:23

    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 :

    —————————————————–
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:my="clr-namespace:WpfApplication1"
    WindowStartupLocation="Manual"
    Title="Window1"
    Height="{SettingBinding Height}"
    Width="{SettingBinding Width}"
    Left="{SettingBinding Left}"
    Top="{SettingBinding Top}">
    —————————————————–

    להגיב