1

I have a static class (Evp), which is located in Models folder. It has a Name string, with getter and setter and a PropertyChangedEventHandler and its code:

public static event PropertyChangedEventHandler StaticPropertyChanged;
private static string _name
public static string Name{
    get => _name;
    set{
        _name = value;
        OnStaticPropertyChanged("Name"); } }
private static void OnStaticPropertyChanged(string propertyName)
    {
        StaticPropertyChanged?.Invoke(null, new PropertyChangedEventArgs(propertyName));
    }

In my XAML file, this is how I tried to bind (it worked in WPF 4.5 if I recall correctly):

<Label Grid.Row="0" Grid.Column="1" TextColor="Beige" Text="{Binding Source={x:Static Models:Evp.Name}}" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontSize="30"></Label>

I specified the Models folder in the ContentPage in XAML:

xmlns:Models="clr-namespace:Rdb.Models;assembly=Rdb"

For some reason, it's not working. What am I doing wrong? Also, how can I set this binding in code-behind?

Martin Zikmund
  • 38,440
  • 7
  • 70
  • 91
Laszlo
  • 53
  • 3
  • 9

1 Answers1

5

To support data binding, your class has to implement the INotifyPropertyChanged interface. Unfortunately, static classes cannot implement interfaces, so your solution will not work.

The solution would be to create a normal class that implements INotifyPropertyChanged and then create a singleton instance of this class which you will register as a resource:

App.Current.Resources["Evp"] = new Evp();

And then you reference it with StaticResource markup extension:

{Binding Name, Source={StaticResource Evp}}

To ensure the class is singleton would be a public static get-only property:

public static Evp Instance {get;} = new Evp();

And you would then also add a private constructor to make sure others cannot create instances of your class:

private Evp()
{
}

The resource would then be set as:

App.Current.Resources["Evp"] = Evp.Instance;

This makes using your class in C# code easier by just using Evp.Instance.

Martin Zikmund
  • 38,440
  • 7
  • 70
  • 91