194

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?

0

12 Answers 12

197

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}"/>
7
  • This answer is more appropriate to my case because I don't want to introduce DependencyObject to my source class. Thanks for the tip! Jun 2, 2009 at 15:30
  • 12
    Note that will enable your text box to push the value back into the static property, but will not update the textbox when the source value changes.
    – Adam Sills
    Jun 2, 2009 at 16:45
  • 1
    That's fine, I just needed the binding from the textbox to the Source in this case. If I want the binding to work the other way, I'm aware of the need for one of these methods: INotifyPropertyChanged, <PropertyName>Changed event or dependency property. Jun 2, 2009 at 20:34
  • 1
    Note: This solution won't work in an MVVM situation, as you generally don't have access to the types of the objects you're binding to. Oct 11, 2013 at 9:06
  • @thomas I would love to get this to work for me but cannot. I posted my dilemma as another question here: stackoverflow.com/questions/34656670/… Jan 7, 2016 at 14:01
130

You can't bind to a static like that. There's no way for the binding infrastructure to get notified of updates since there's no DependencyObject (or object instance that implement INotifyPropertyChanged) involved.

If that value doesn't change, just ditch the binding and use x:Static directly inside the Text property. Define app below to be the namespace (and assembly) location of the VersionManager class.

<TextBox Text="{x:Static app:VersionManager.FilterString}" />

If the value does change, I'd suggest creating a singleton to contain the value and bind to that.

An example of the singleton:

public class VersionManager : DependencyObject {
    public static readonly DependencyProperty FilterStringProperty =
        DependencyProperty.Register( "FilterString", typeof( string ),
        typeof( VersionManager ), new UIPropertyMetadata( "no version!" ) );
    public string FilterString {
        get { return (string) GetValue( FilterStringProperty ); }
        set { SetValue( FilterStringProperty, value ); }
    }

    public static VersionManager Instance { get; private set; }

    static VersionManager() {
        Instance = new VersionManager();
    }
}
<TextBox Text="{Binding Source={x:Static local:VersionManager.Instance},
                        Path=FilterString}"/>
4
  • 5
    Really? I've been able to do bind to the static Int32.MaxValue which is very similar to my sample: <TextBox Text={Binding Source={x:Static sys:Int32.MaxValue}, Mode=OneWay}" /> Is that working because it's one way? Jun 1, 2009 at 19:36
  • 2
    Yeah, any two way binding requires a Path property value on the binding. Source needs to be an object that contains the property specified by Path. Specifying OneWay removes that restriction.
    – Adam Sills
    Jun 1, 2009 at 21:30
  • Also, sorry for the late update, but I updated the above answer with a sample.
    – Adam Sills
    Jun 1, 2009 at 21:37
  • Is there a way to bind a static string. I have a mutibinding and one of the input is a fixed string. Jul 9, 2010 at 11:12
42

In .NET 4.5 it's possible to bind to static properties, read more

You can use static properties as the source of a data binding. The data binding engine recognizes when the property's value changes if a static event is raised. For example, if the class SomeClass defines a static property called MyProperty, SomeClass can define a static event that is raised when the value of MyProperty changes. The static event can use either of the following signatures:

public static event EventHandler MyPropertyChanged; 
public static event EventHandler<PropertyChangedEventArgs> StaticPropertyChanged; 

Note that in the first case, the class exposes a static event named PropertyNameChanged that passes EventArgs to the event handler. In the second case, the class exposes a static event named StaticPropertyChanged that passes PropertyChangedEventArgs to the event handler. A class that implements the static property can choose to raise property-change notifications using either method.

2
22

As of WPF 4.5 you can bind directly to static properties and have the binding automatically update when your property is changed. You do need to manually wire up a change event to trigger the binding updates.

public class VersionManager
{
    private static String _filterString;        

    /// <summary>
    /// A static property which you'd like to bind to
    /// </summary>
    public static String FilterString
    {
        get
        {
            return _filterString;
        }

        set
        {
            _filterString = value;

            // Raise a change event
            OnFilterStringChanged(EventArgs.Empty);
        }
    }

    // Declare a static event representing changes to your static property
    public static event EventHandler FilterStringChanged;

    // Raise the change event through this static method
    protected static void OnFilterStringChanged(EventArgs e)
    {
        EventHandler handler = FilterStringChanged;

        if (handler != null)
        {
            handler(null, e);
        }
    }

    static VersionManager()
    {
        // Set up an empty event handler
        FilterStringChanged += (sender, e) => { return; };
    }

}

You can now bind your static property just like any other:

<TextBox Text="{Binding Path=(local:VersionManager.FilterString)}"/>
4
  • 1
    The VersionManager class can be static and everything still works. Note the braces in the path definition Path=(local:VersionManager.FilterString). Does anyone know why they are actually needed? Sep 26, 2019 at 9:13
  • 2
    The braces in the path definition are needed because the property is static, see here Sep 26, 2019 at 9:54
  • @Matt how do I know my wpf version?
    – paraJdox1
    Jun 9, 2021 at 11:24
  • Also note that unlike 'normal' binding you cannot omit Path= here
    – nevermind
    Sep 29, 2021 at 14:16
15

There could be two ways/syntax to bind a static property. If p is a static property in class MainWindow, then binding for textbox will be:

1.

<TextBox Text="{x:Static local:MainWindow.p}" />

2.

<TextBox Text="{Binding Source={x:Static local:MainWindow.p},Mode=OneTime}" />
9

You can use ObjectDataProvider class and it's MethodName property. It can look like this:

<Window.Resources>
   <ObjectDataProvider x:Key="versionManager" ObjectType="{x:Type VersionManager}" MethodName="get_FilterString"></ObjectDataProvider>
</Window.Resources>

Declared object data provider can be used like this:

<TextBox Text="{Binding Source={StaticResource versionManager}}" />
8

If you are using local resources you can refer to them as below:

<TextBlock Text="{Binding Source={x:Static prop:Resources.PerUnitOfMeasure}}" TextWrapping="Wrap" TextAlignment="Center"/>
7

Right variant for .NET 4.5 +

C# code

public class VersionManager
{
    private static string filterString;

    public static string FilterString
    {
        get => filterString;
        set
        {
            if (filterString == value)
                return;

            filterString = value;

            StaticPropertyChanged?.Invoke(null, FilterStringPropertyEventArgs);
        }
    }

    private static readonly PropertyChangedEventArgs FilterStringPropertyEventArgs = new PropertyChangedEventArgs (nameof(FilterString));
    public static event PropertyChangedEventHandler StaticPropertyChanged;
}

XAML binding (attention to braces they are (), not {})

<TextBox Text="{Binding Path=(yournamespace:VersionManager.FilterString)}" />
3
  • Made a slight change to your code to properly call the EventHandler. Sep 8, 2018 at 0:41
  • 1
    Tried a lot of different solutions and this one worked. The PropertyChangedEventHandler is what worked for me. Cheers.
    – Mgamerz
    Sep 24, 2019 at 23:40
  • Using this for a DataTrigger. Same - tried several methods and this worked
    – Jeff
    May 1, 2022 at 19:32
5

Leanest answer (.net 4.5 and later):

    static public event EventHandler FilterStringChanged;
    static string _filterString;
    static public string FilterString
    {
        get { return _filterString; }
        set
        {
            _filterString= value;
            FilterStringChanged?.Invoke(null, EventArgs.Empty);
        }
    }

and XAML:

    <TextBox Text="{Binding Path=(local:VersionManager.FilterString)}"/>

Don't neglect the brackets

2

Look at my project CalcBinding, which provides to you writing complex expressions in Path property value, including static properties, source properties, Math and other. So, you can write this:

<TextBox Text="{c:Binding local:VersionManager.FilterString}"/>

Goodluck!

0

Another solution is to create a normal class which implements PropertyChanger like this

public class ViewProps : PropertyChanger
{
    private string _MyValue = string.Empty;
    public string MyValue
    {
        get { 
            return _MyValue
        }
        set
        {
            if (_MyValue == value)
            {
                return;
            }
            SetProperty(ref _MyValue, value);
        }
    }
}

Then create a static instance of the class somewhere you wont

public class MyClass
{
    private static ViewProps _ViewProps = null;
    public static ViewProps ViewProps
    {
        get
        {
            if (_ViewProps == null)
            {
                _ViewProps = new ViewProps();
            }
            return _ViewProps;
        }
    }
}

And now use it as static property

<TextBlock  Text="{x:Bind local:MyClass.ViewProps.MyValue, Mode=OneWay}"  />

And here is PropertyChanger implementation if necessary

public abstract class PropertyChanger : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
    {
        if (object.Equals(storage, value)) return false;

        storage = value;
        OnPropertyChanged(propertyName);
        return true;
    }

    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
0

Suppose you have a class as follow:

public static class VersionManager 
{
    public static string FilterString;
}

You can bind your static variable in this way:

<TextBox Text = {x:Static local:VersionManager.FilterString }/>
1
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Mar 15, 2022 at 1:22

Not the answer you're looking for? Browse other questions tagged or ask your own question.