Two-way bindings require use of the Path
value in the Binding
. For binding to static properties, they require a very specific syntax. In your case, the XAML should look like:
<TextBlock Name="Test"
Text="{Binding Path=(status:Status.IsConnected), Mode=TwoWay}">
Note the use of parentheses around the path. This indicates to the parser to interpret the class name correctly.
Your code-behind is correct. You have implemented a single StaticPropertyChanged
event, analogous to the instance version PropertyChanged
, and which WPF will use for the binding. Note that you could also have implemented an IsConnectedChanged
event instead. WPF would have accepted that as well.
Finally I note that guidance I've read recommends using a singleton pattern if possible and/or appropriate. While WPF now supports binding to static properties, binding to a property on an actual object is still preferred.
See this relevant blog post for more details: WPF 4.5: Binding and change notification for static properties
EDIT:
You didn't ask about how to create a binding in code-behind. However, because I was looking at a different question earlier today involving setting up a binding in code-behind, I decided to look into how this would work for static properties.
For instance properties, it's simple because you can specify an object for the Binding.Source
property. But for a static property, this is null
(*). Instead, you have to specify the property via the Binding.Path
property:
Binding binding = new Binding();
binding.Path = new PropertyPath(typeof(Status).GetProperty("IsConnected");
binding.Mode = BindingMode.TwoWay;
This passes a PropertyInfo
object representing the property you're binding to, to the PropertyPath(object)
constructor overload.
(*) Or rather, it can be null. A sort of hack you can use when binding to static properties is to specify an actual instance of the class containing the static property. Of course, you can't do this for static
classes, or for classes for which you don't happen to have a handy instance lying around to use. But if you do, then you can actually bind to the static property just like you'd bind to an instance property, specifying any instance of the class containing the static property, and the name of the static property (as if it were an instance property).