Binding to static property

Anthony Brien picture Anthony Brien · Jun 1, 2009 · Viewed 172.3k times · Source

I'm having a hard time binding a simple static string property to a TextBox.

Here's the class with the static property:

public class VersionManager
{
    private static string filterString;

    public static string FilterString
    {
        get { return filterString; }
        set { filterString = value; }
    }
}

In my xaml, I just want to bind this static property to a TextBox:

<TextBox>
    <TextBox.Text>
        <Binding Source="{x:Static local:VersionManager.FilterString}"/>
    </TextBox.Text>
</TextBox>

Everything compiles, but at run time, I get the following exception:

Cannot convert the value in attribute 'Source' to object of type 'System.Windows.Markup.StaticExtension'. Error at object 'System.Windows.Data.Binding' in markup file 'BurnDisk;component/selectversionpagefunction.xaml' Line 57 Position 29.

Any idea what I'm doing wrong?

Answer

Thomas Levesque picture Thomas Levesque · Jun 2, 2009

If the binding needs to be two-way, you must supply a path.

There's a trick to do two-way binding on a static property, provided the class is not static : declare a dummy instance of the class in the resources, and use it as the source of the binding.

<Window.Resources>
    <local:VersionManager x:Key="versionManager"/>
</Window.Resources>
...

<TextBox Text="{Binding Source={StaticResource versionManager}, Path=FilterString}"/>