Binding to static property
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}"/>
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}"/>
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.