Search code examples
c#xamluwpwin-universal-appuwp-xaml

C# Binding global static string to UWP Textblock


everybody.

Does anyone knows how to bind global static string to UWP Textblock, with propertychange update in control?

I have tried a lot of things, such as:

Text="{Binding Path={local:AppSettings.StorageFolder}, Mode=OneWay}"
Text="{x:Bind Path=(local:AppSettings.StorageFolder), RelativeSource={RelativeSource Self}, Mode=OneWay}"

And none works. Always some error comes up, like: "Nested types are not supported and Value does not fall within the expected range"

I have managed to bind it to non static value in my class:

Text="{x:Bind viewModel.MyValue, Mode=OneWay}"

Any solution to this?

Thanx.


Solution

  • You simply can't bind to a static property in UWP the same way as you can in WPF. There is no x:Static markup extension available.

    You have some options:

    If the DataContext of the element is an instance of the type in which the static property is defined, you could bind to a static property as usual:

    <TextBlock Text="{Binding MyStaticProperty}" />
    
    public sealed partial class BlankPage1 : Page
    {
        public BlankPage1()
        {
            this.InitializeComponent();
            this.DataContext = this;
        }
    
        public static string MyStaticProperty { get { return "Static..."; } }
    }
    

    If the static property is defined in another class, your best option would be to wrap the static property in a non-static one:

    public sealed partial class BlankPage1 : Page
    {
        public BlankPage1()
        {
            this.InitializeComponent();
            this.DataContext = this;
        }
    
        public static string MyWrapperProperty { get { return MyStaticClass.MyStaticProperty; } }
    }
    
    public static class MyStaticClass
    {
        public static string MyStaticProperty { get { return "Static..."; } }
    }
    

    If you want property change notifications it makes no sense to bind to a static property at all because the source object of a property must implement the INotifyPropertyChanged interface for you to be able to refresh the target property dynamically by raising the PropertyChanged event.

    You could still wrap the static property in a non-static one of a view model that implements the INotifyPropertyChanged interface:

    public class ViewModel : INotifyPropertyChanged
    {
        public string MyNonStaticProperty
        {
            get { return MyStaticClass.MyStaticProperty; }
            set { MyStaticClass.MyStaticProperty = value; NotifyPropertyChanged(); }
        }
    
        //...
    }
    
    public static class MyStaticClass
    {
        public static string MyStaticProperty { get; set; }
    }
    

    You will obviosuly need to call NotifyPropertyChanged("MyNonStaticProperty") from the view model class whenever you want to refresh the target property in the view.