-2

In my WPF app, I have a class with Static strings as follows and I refer the same from the XAML. My intention is to update these static strings and the UI texts should reflect the update.

public class StaticStrings
{
    public static string text1= "sample 1";
    public static string text2= "sample 2";
    public static string text3= "sample 3";
}

From the XAML I refer them as below:

<Label 
                    Content="{x:Static local:StaticStrings.text1}" 
                    Background="Transparent" 
                    Margin="5,0,18,3"
                    />
<Button x:Name="btn" 
                    Click="btn_MouseUp"
                    ToolTip="{x:Static local:StaticStrings.text2}"
                    />

During runtime, I would update the texts of StaticStrings and wish to see them reflected in the UI. How to achieve this?

Shameel Mohamed
  • 607
  • 5
  • 23

1 Answers1

1
  1. Modify your StaticString class to support change notifications and expose public properties to bind to:

     public class StaticStrings
     {
         private static string text1 = "sample 1";
         public static string Text1
         {
             get { return text1; }
             set { text1 = value; NotifyStaticPropertyChanged(); }
         }
    
         private static string text2 = "sample 2";
         public static string Text2
         {
             get { return text2; }
             set { text2 = value; NotifyStaticPropertyChanged(); }
         }
    
         private static string text3 = "sample 3";
         public static string Text3
         {
             get { return text3; }
             set { text3 = value; NotifyStaticPropertyChanged(); }
         }
    
         public static event PropertyChangedEventHandler StaticPropertyChanged;
    
         private static void NotifyStaticPropertyChanged([CallerMemberName] string propertyName = null)
         {
             StaticPropertyChanged?.Invoke(null, new PropertyChangedEventArgs(propertyName));
         }
     }
    
  2. Bind to the public properties:

     <Label 
             Content="{Binding Path=(local:StaticStrings.Text1)}" 
             Background="Transparent" 
             Margin="5,0,18,3"
             />
     <Button x:Name="btn" 
             Click="btn_MouseUp"
             ToolTip="{Binding Path=(local:StaticStrings.Text2)}"
             />
    
mm8
  • 163,881
  • 10
  • 57
  • 88
  • The thing is the strings can be any number. This seems really tiresome. Is there a way to trigger the PropertyChanged event automatically for all the props. – Shameel Mohamed Nov 18 '21 at 11:28
  • [Fody](https://github.com/Fody/PropertyChanged) injects code which raises the `PropertyChanged` event into property setters of classes which implement `INotifyPropertyChanged` at build time. Don't know if it works with static properties. Otherwise you will have to implement these by your own like I did in my example. This is nothing strange or unusal. – mm8 Nov 19 '21 at 14:22