Search code examples
c#wpfbindingstatic

Wpf 4.8 binding to static property


I create viewbox programmaticaly. How to bind this control programaticaly to static property of non static class.

var bindingHeight = new Binding("viewbox_height");
        bindingHeight.Source = Config.viewbox_height;
        bindingHeight.Mode = BindingMode.TwoWay;
        bindingHeight.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
        MyViewbox.SetBinding(Viewbox.HeightProperty, bindingHeight);


public class Config
{
    public static event EventHandler<PropertyChangedEventArgs> StaticPropertyChanged;
    public static void OnPropertyChanged([CallerMemberName] string propertyname = null)
    {   
   StaticPropertyChanged?.Invoke(null, new PropertyChangedEventArgs(propertyname));
    }

This way doesnt work.


Solution

  • Set the source to an instance of a Config:

    var bindingHeight = new Binding("viewbox_height");
    bindingHeight.Source = new Config();
    bindingHeight.Mode = BindingMode.TwoWay;
    bindingHeight.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
    MyViewbox.SetBinding(Viewbox.HeightProperty, bindingHeight);