Binding to static class property
C#WpfBindingTextblockC# Problem Overview
I want to bind a textblock text to a property of a static class. Whenever the property value of the static class changes, it should reflect to the textblock which is on the other window or custom control.
C# Solutions
Solution 1 - C#
You can bind to ANY property on a static class using the x:Static markup extension but if thy do not implement any change tracking, it might cause errors on the refresh!
<TextBlock Text="{Binding Source={x:Static sys:Environment.MachineName}}" />
Solution 2 - C#
For those who use nested static classes to organize/seperate constants. If you need to Bind into nested static classes, It seems you need to use a plus (+) operator instead of the dot (.) operator to access the nested class:
{Binding Source={x:Static namespace:StaticClass+NestedStaticClasses.StaticVar}}
Example:
public static class StaticClass
{
public static class NestedStaticClasses
{
public static readonly int StaticVar= 0;
}
}
Solution 3 - C#
This has worked for me:
Text="{Binding Source={x:Static MyNamespace:MyStaticClass.MyProperty}, Mode=OneWay}"
Without Mode=OneWay
I got an exception.
Solution 4 - C#
It worked for me!
When you have static class with static property like this
namespace App.Classes
{
public static class AppData
{
private static ConfigModel _configModel;
public static ConfigModel Configuration
{
get { return _configModel; }
set { _configModel = value; }
}
}
public class ConfigModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private bool _text = true;
public bool Text
{
get { return _text ; }
set {
_text = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Text"));
}
}
}
}
You can bind it to xaml like this.
xmlns:c="clr-namespace:App.Classes"
<TextBlock Text="{Binding Path=Text, Source={x:Static c:AppData.Configuration}}"/>