WPF Binding to a property of a static class
Binding to a property of a static class is quite straight forward.
The binding string looks like this:
{x:Static s:MyStaticClass.StaticValue2}
For an example do this:
- Create a new folder in your project called Statics.
- Add the following class to the Statics folder.
using System; namespace BindingToStaticClassExample.Statics { public static class MyStaticClass { static MyStaticClass() { Title = "Binding to properties of Static Classes"; StaticValue1 = "Test 1"; StaticValue2 = "Test 2"; StaticValue3 = "Test 3"; } public static String Title { get; set; } public static String StaticValue1 { get; set; } public static String StaticValue2 { get; set; } public static String StaticValue3 { get; set; } } }
- Add a reference to the BindingToStaticClassExample.Statics namespace. (See line 4.)
- Bind the title to the Title string value of MyStaticClass.
- Change the <Grid> to a <StackPanel> (not required just for ease of this example).
- Add TextBox elements and bind them to the two string values in MyStaticClass object.
<Window x:Class="BindingToStaticClassExample.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:BindingToStaticClassExample.Statics" Title="{x:Static s:MyStaticClass.Title}" Height="350" Width="525"> <StackPanel> <TextBox Text="{x:Static s:MyStaticClass.StaticValue1}" /> <TextBox Text="{x:Static s:MyStaticClass.StaticValue2}" /> <!-- Not supported and won't work <TextBox> <TextBox.Text> <Binding Source="{x:Static s:MyStaticClass.StaticValue3}" /> </TextBox.Text> </TextBox> --> </StackPanel> </Window>
You now know how to bind to properties of a static class.
Thanks... It took hours to find this
Hi,
Still wont work for me.
I'm changing the state of IsBluethON from another event, but the binding won't work?
Can anyone correct where I'm doing it wrong?
Thanks
John
Two things:
1. There is a link right above the Submit Comment button that says: How to post code in comments?
2. Binding to a static variable is much easier than "updating" the binding on a static variable. One time binding is easy. But to have a binding that updates, you need to implement INotifyPropertyChanged and call NotifyPropertyChanged("IsBlueToothOn") when the value changes.
Usually I only bind to a static variable if I don't need to update the binding. Now, it might not be appropriate to implement INotifyPropertyChanged on your static class. If it is, do it. But if it isn't, instead, I assume there is a BlueToothStateChanged event of some kind somewhere. Create a ViewModel that implements INotifyPropertyChanged. Have that ViewModel subscribe to the BlueToothStateChanged event and on event. The method it subscribes with calls NotifyPropertyChanged("IsBlueToothOn"), but have an IsBlueToothOn property in your ViewModel that wraps your static IsBlueToothOn property.
Hope that helps.