I'm having a hard time binding a simple static string property to a text box.
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 text box:
<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?
Right variant for .NET 4.5 +
C# code
XAML binding (attention to braces they are (), not {})
In .NET 4.5 it's possible to bind to static properties, read more
If you are using local resources you can refer to them as below:
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.
You can now bind your static property just like any other:
You can use
ObjectDataProvider
class and it'sMethodName
property. It can look like this:Declared object data provider can be used like this:
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 implementINotifyPropertyChanged
) involved.If that value doesn't change, just ditch the binding and use
x:Static
directly inside theText
property. Defineapp
below to be the namespace (and assembly) location of the VersionManager class.If the value does change, I'd suggest creating a singleton to contain the value and bind to that.
An example of the singleton: