简体   繁体   中英

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.

At least you made a mistake in setting Binding.Source . In the case of usual instance property, it should be the object which has that property, in your case, the instance of "Config". In the case of static property, you don't need to set Binding.Source .

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM