[WPF] Binding to application settings using a markup extension

Hi, this is my first post on this blog, I hope you will enjoy it ;-). If you want to know a few things about me, please check out this page.

The end-user of any application expects that his preferences (window size, state of this or that option…) are saved to be restored at the next run : that’s why .NET 2.0 introduced application settings as a unified way to persist these settings. However, if there are many settings, it can be a real hassle for the developper to handle them… even with the help of the Settings class generated by Visual Studio, there is still quite a lot of code to write to apply these settings to the user interface, then update them according to user modifications.

In Windows Forms, it was possible to define bindings between control properties and application settings, but it wasn’t very intuitive, and wasn’t very widely used (I’m not so sure about that, but I actually never saw it used by anyone…).

With WPF, we can do something similar in a much more elegant way… although it’s not “officially” documented, it is possible to create bindings to application settings in XAML. For instance, to persist the window size and position in application settings, many blogs suggest this approach :

<Window x:Class="WpfApplication1.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}">

(In that example, Height, Width, Top and Left are application settings)

This code does work, but honestly, do you feel like writing this for every setting of the application ? It’s too verbose, not intuitive, and makes the code harder to read…

Of course, I’m not saying this idea is bad… but it’s very easy to improve it, by creating our own « markup extension ». In this post I’m going to explain how to write a class that inherits Binding, and allows to bind easily to application settings.

« Markup extension » are objects that can be used in XAML to retrieve values. They are used all the time in WPF : for instance, Binding, StaticResource and DynamicResource are markup extensions.

It’s quite easy to define your own markup extension, by creating a class that inherits the abstract MarkupExtension class, and implements the ProvideValue method. In our case, most of what we need is already implemented in the Binding class (which indirectly inherits MarkupExtension). So we’re just going to inherit Binding, and initialize the necessary properties in order to bind to application settings :

using System.Windows.Data;

namespace WpfApplication1
    public class SettingBindingExtension : Binding
        public SettingBindingExtension()

        public SettingBindingExtension(string path)

        private void Initialize()
            this.Source = WpfApplication1.Properties.Settings.Default;
            this.Mode = BindingMode.TwoWay;

Note the « Extension » suffix at the end of the class name : by convention, most markup extensions have this suffix (Binding is an exception…). It can be omitted when using the class in XAML (similarly to attributes, for which the « Attribute » suffix can be omitted).

In that class, we defined two constructors, matching those of the Binding class. We don’t need to redefine the ProvideValue method, because the one implemented in the Binding class suits us perfectly (and anyway it is marked as sealed, so we couldn’t override it even if we wanted to…). The part that actually makes the code work is the Initialize method. It initializes the Source property, so that the Path of the binding maps to the specified setting, and sets Mode to TwoWay so that application settings are automatically updated from the UI. The point of doing this is that we don’t have to set these properties every time we bind to a setting…

To illustrate the usage of this markup extension, let’s go back to the previous example, and replace the Bindings with the SettingBinding extension :

<Window x:Class="WpfApplication1.Window1"
        Height="{my:SettingBinding Height}"
        Width="{my:SettingBinding Width}"
        Left="{my:SettingBinding Left}"
        Top="{my:SettingBinding Top}">

Isn’t it much clearer, more readable, and shorter to write ?

And of course, to make it work, let’s not forget to save the settings in the application’s Exit event…

        private void Application_Exit(object sender, ExitEventArgs e)

That’s it ! the window size and position are now saved, and restored when the application is started again, without having to write anything more…

Download source code

Update : If you understand French and want to know more about markup extensions, I suggest you read my tutorial on this topic : Les markup extensions en WPF

32 thoughts on “[WPF] Binding to application settings using a markup extension”

  1. Looks nice and it works. The problem for me is that the designer doesn”t like it and thinks there is an error.

    Error 2 No constructor for type ”SettingBindingExtension” has 1 parameters.

    1. Really ? for me it works fine in the designer… What”s very strange is that the statement in the error message is clearly wrong, since there IS a constructor with one argument…
      Try to rebuild the project and re-open the designer, and if it still doesn”t work, you can always specify the Path property explicitly :

      Height=”{my:SettingBinding Path=Height}”

    2. I am having the exactly same problem with a markup extension I created. I found this post while searching for the solution… do you have one, please? Looks like a bug of VS to me…

      1. Hi Mek,

        Actually the WPF designer has trouble with markup extensions that are defined in the same assembly as the current project… So you have 2 options :
        – Put the markup extension in a separate assembly
        – Use the default constructor and specify the Path property explicitly :

        Height="{my:SettingBinding Path=Height}"

  2. Your solution works great, but I have one question: is there any way to access Properties.Setting.Default object outside from its owner project? E.g. I have simple Class Library, which contains yours SettingBinding Markup Extension and I can’t write there this line:

    this.Source = WpfApplication1.Properties.Settings.Default;

    because from the one hand my Settings object has internal modifier and from the other hand I want to have universal SettingBindingExtension, no only connected with one default WpfApplication1 project. I also tried to resign from that universal conception, but when I want to use:

    [assembly: XmlnsDefinition(“http://schemas.microsoft.com/winfx/2006/xaml/presentation”, “MyNamespace”)]

    Visual Studio report an error, that SettingBinding is not registered in default namcespace. Interesting thing is that if I have the same XmlnsDefinition in my Class Library (instead of in my main project) this problem doesn’t exist and everything works fine (besides that I can’t use then Properties.Settings.Default statement in that Class Library). Any suggestion will be appreciated.

    1. Hi Paul,

      Indeed, this markup extension can”t work from another assembly, at least in its current state. However, it”s pretty easy to modify it to make it “universal”, or close to it…

      Here”s the solution I came up with: instead of explicitly using WpfApplication1.Properties.Settings.Default as the source, I created a new SettingsManager class with a static Settings property. The class initializes the Settings property using reflection in its static constructor, but it is possible to explicitly assign it when the program starts.

      I posted the new code here: http://pastebin.com/T7waZ2mL


        1. @Roger I honestly have no idea… This post is 10 years old and I don’t remember anything about it. However, it looks like you can use Assembly.GetEntryAssembly() instead of AssemblyManager.GetEntryAssembly()

  3. Doesn”t this have the issue that 2 windows will overwrite each other”s settings? So you need to define the properties as Window1_Height, Window2_Height etc

  4. Great idea! I couldn’t get the App.Properties.Settings.Default to work and so moved it to an independent config file and added default values to the bindings e.g.:

    Top=”{local:XSettings Top, 45}”

    here is the XSettingsExtension class:

    public class XSettingsExtension : Binding
    public static XDocument XDoc;

    public XSettingsExtension()

    public XSettingsExtension(string path)
    : base(path)

    public XSettingsExtension(string path, string _default)
    : base(path)

    int i;
    double d;

    if (int.TryParse(_default, out i))
    FallbackValue = i;
    TargetNullValue = i;

    else if (double.TryParse(_default, out d))
    FallbackValue = d;
    TargetNullValue = d;

    FallbackValue = _default;
    TargetNullValue = _default;

    private void Initialize()
    if (XDoc == null)
    string XDocRoot = Assembly.GetExecutingAssembly().GetName().Name;
    string fn = System.IO.Path.Combine(
    XDocRoot );

    DirectoryInfo di = new DirectoryInfo(fn);
    if (!di.Exists)

    fn = System.IO.Path.Combine(fn, “user.config”);
    FileInfo fi = new FileInfo(fn);
    if (fi.Exists)
    XDoc = XDocument.Load(fn);

    XDoc = new XDocument(new XElement(XDocRoot));

    if (XDoc.Root.Element(this.Path.Path) == null)
    XDoc.Root.Add(new XElement(this.Path.Path));

    this.Path.Path = “Root.Element[” + this.Path.Path + “].Value”;
    this.Source = XDoc;
    this.Mode = BindingMode.TwoWay;

  5. This SettingBindingExtension method works as shown for me. Very nice. Thanks.

    I was unable to type an email into this web page. I was able to paste an email from the clipboard into this web page.

  6. The problem is that it doesn’t work with Converter:
    Error 1 Object of type ‘System.Windows.StaticResourceExtension’ cannot be converted to type ‘System.Windows.Data.IValueConverter’.

    1. Sorry for the late reply, for some reason I didn’t get the email notification…

      What are you trying to do exactly? Could you post your XAML code?

  7. Hi Thomas I am trying to read about Markup Extension on MSDN and various blog but could not understand clearly.
    Can you please explain little about that with example and what is the use of that.

    1. Mehul, I don’t know how I can explain it better than MSDN… Basically it’s a thing like “{Binding}” or “{DynamicResource}”, that you can use in XAML to obtain a value at runtime. A custom markup extension lets you define what is return by overriding the ProvideValue method.
      I have a detailed article here, but it’s in French…

    1. Nevermind, I’ve dug a little through your french article on Markup Extensions and answered my own question!
      Very nice stuff!!

  8. Hi, I think this way is nice but I´m looking for something else. My problem is I´m trying to bound “Window State” property to a value in the settings file like this:

    WindowState=”{Binding Source={x:Static p:Settings.Default}, Path=Maximized, Mode=TwoWay, Converter={StaticResource WindowStateConv}}”

    The Converter Code will be as follow

        public class WindowStateConverter : IValueConverter
            public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
                if (System.Convert.ToBoolean(value))
                    return System.Windows.WindowState.Maximized;
                return System.Windows.WindowState.Minimized;
            public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
                throw new NotImplementedException();

    When I run the program it throw an XamlParseException saying it apear an exception asigning a value in’System.Windows.StaticResourceExtension’, it also says
    {“Can´t faund the resource named ‘WindowStateConv’. Resource´s names distinguish between capital leters.”}

    I actually traslate the last expresion from spanish so it could be wrong but it is basically my problem, could somebody help me

    1. Did you add the converter to the window’s resources? I can’t think of any other reason why it would throw that error.

    2. No need for a converter. The bloggers code works out of the box for WindowsState as well.


      Height="{local:SettingBinding Height}"
      Width="{local:SettingBinding Width}"
      Left="{local:SettingBinding Left}"
      Top="{local:SettingBinding Top}"
      WindowState="{local:SettingBinding WindowState}"

      Now in your application settings, instead of binding “Height” to type “double”:

      you will bind “WindowState” to type “System.Windows.WindowState” found by browsing to WindowsPresentationFrameWork.

  9. Dear Thomas,
    Thanks for your great work which give me a Concise and practical way to obtain task. What I wondered is: Using your Extension, Can I get the WPF MenuItem work? The code is as flowing:

    What I want is by using your extension, the application can remember the user checked preferences (All of the three…) , and saved them to be restored at the next run.
    Can I get it by using your tool? If I can, how?
    Thanks again.
    Sincerely Lingyong He

    1. Hi,

      The code in your comment was stripped by WordPress… please post it to Gist instead

  10. Nine years late I’d like to thank you for your post and add a comment:

    For days I’ve been unsuccessful at getting binding and settings to work together. Finally, by scouring your code I got it to work.

    You’ve got to create the settings in the Properties (or Settings.settings file) first. Then you can use the binding.

    1. @Eric, yes, I should have been more explicit about that… it seemed obvious in my mind, but I guess it wasn’t necessarily obvious for readers.

    1. Hi iFeng Huan,

      Yes, it should, since the settings class inherits from ApplicationSettingsBase, which implements INotifyPropertyChanged.

  11. I have been writing large business critical WPF applications for about 12 years now and as much time as I have dedicated out of my life to master the beast that WPF is, I am always grateful that Google can bring me to pages like yours. You refreshed my memory for the keywords “Markup Extension” that for the life of me I could not remember this Saturday morning. Have a good weekend and thanks for sharing.

Leave a Reply

Your email address will not be published. Required fields are marked *