Update Static Property Binding

The application is developed using C # and WPF. I have data binding to a static property of a non-static class. When the application is launched, the binding works well, but if I change the bool of the binding, the view does not update. How can I update the binding of this static property? NotifyChanged-Events do not affect.

Grade:

public class ViewTemplateManager : NotifyBase { public static bool CanResizeColumns { get; set; } static ViewTemplateManager() { CanResizeColumns = true; } 

View:

 <Thumb x:Name="PART_HeaderGripper" IsEnabled="{Binding Source={x:Static Member=viewManager:ViewTemplateManager.CanResizeColumns}}" 
+6
source share
4 answers

The only way to do this is if you have a link to the associated BindingExpression .

Assuming you have a Thumb link in your code, it will look like this:

 var bindingExpression = thumb.GetBindingExpression(Thumb.IsEnabledProperty); if (bindingExpression != null) bindingExpression.UpdateTarget(); 

It is best to use a singleton pattern, for example:

 public class ViewTemplateManager : NotifyBase { public bool CanResizeColumns { get; set; } public static ViewTemplateManager Instance { get; private set; } static ViewTemplateManager() { Instance = new ViewTemplateManager(); } private ViewTemplateManager() { CanResizeColumns = true; } } 

Then bind yourself like this:

 <Thumb x:Name="PART_HeaderGripper" IsEnabled="{Binding Source={x:Static viewManager:ViewTemplateManager.Instance}, Path=CanResizeColumns}}" 

Then you just need to raise the INotifyPropertyChanged.PropertyChanged event when CanResizeColumns changes.

+6
source

Unfortunately, there is no direct equivalent to the INotifyPropertyChanged notification INotifyPropertyChanged for a static property.

There are several options, including:

  • Create an instance level property that returns a static member. Use a special mechanism to notify change instances when an instance can raise a PropertyChanged event. This can become ugly and lead to a memory leak if you are not careful about unsubscribing or using the weak event pattern.
  • Move the static property to a singleton and place it as an instance on a singleton instance. This allows this instance to raise PropertyChanged events as usual.
+2
source

You can either implement the properties using Singleton , on which the property is not static, or just make it non-static, but you just create one instance in the App instance for example (I would go with the latter). In any case, you can implement INotifyPropertyChanged again.

+2
source

I think this is a simpler solution:

Class property:

 private static bool isEnabled; //there is Your static public bool IsEnabled { get { return isEnabled; } set { isEnabled = value; RaisePropertyChanged("IsEnabled"); //OnPropertyChanged or something } } 

XAML:

 <Button IsEnabled="{Binding IsEnabled}"/> 
0
source

Source: https://habr.com/ru/post/890782/


All Articles