How can I bind a xaml property to a static variable in another class?

You can't actually bind to a static property (INotifyPropertyChanged makes sense on instances only), so this should be enough...

{x:Static my:MyTestStaticClass.MyProperty}  

or e.g.

<TextBox Text="{x:Static my:MyTestStaticClass.MyProperty}" Width="500" Height="100" />  

make sure you include the namespace - i.e. define the my in the XAML like xmlns:my="clr-namespace:MyNamespace"


EDIT: binding from code
(There're some mixed answers on this part so I thought it made sense to expand, have it in one place)


OneTime binding:

You could just use textBlock.Text = MyStaticClass.Left (just careful where you place that, post-init)

TwoWay (or OneWayToSource) binding:

Binding binding = new Binding();
//binding.Source = typeof(MyStaticClass);
// System.InvalidOperationException: 'Binding.StaticSource cannot be set while using Binding.Source.'
binding.Path = new PropertyPath(typeof(MyStaticClass).GetProperty(nameof(MyStaticClass.Left)));
binding.Mode = BindingMode.TwoWay;
binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
this.SetBinding(Window.LeftProperty, binding);

...of course if you're setting Binding from the code remove any bindings in XAML.

OneWay (property changes from the source):

And if you'd need to update the target (i.e. the control's property, Window.Left in this case) on the source property changes, that can't be achieved with the static class (as per my comment above, you'd need the INotifyPropertyChanged implemented, so you could just use a wrapper class, implement INotifyPropertyChanged and wire that to a static property of your interest (providing you know how to track you static property's changes, i.e. this is more of a 'design' issue from this point on, I'd suggest redesigning and putting it all within one 'non-static' class).


First of all you can't bind to variable. You can bind only to properties from XAML. For binding to static property you can do in this way (say you want to bind Text property of TextBlock) -

<TextBlock Text="{Binding Source={x:Static local:YourClassName.PropertyName}}"/>

where local is namespace where your class resides which you need to declare above in xaml file like this -

xmlns:local="clr-namespace:YourNameSpace"

You can use the newer x:Bind to do this simply using:

<TextBlock Text="{x:Bind YourClassName.PropertyName}"/>

Tags:

C#

Wpf

Xaml