简体   繁体   中英

Binding static property in code behind

I am trying to follow this article , the only difference is that I am creating and binding the control in code behind. Unfortunately it's not working. Here is my sample code :

 public partial class ShellWindow
 {
      private static Visibility progressbarVisibility = Visibility.Collapsed;
      public static Visibility ProgressbarVisibility
      {
           get { return progressbarVisibility; }
           set
           {
               if (progressbarVisibility == value) return;
               progressbarVisibility = value;
               RaiseStaticPropertyChanged("ProgressbarVisibility");
           }
      }
      public static event EventHandler<PropertyChangedEventArgs> StaticPropertyChanged;
      public static void RaiseStaticPropertyChanged(string propName)
      {
           EventHandler<PropertyChangedEventArgs> handler = StaticPropertyChanged;
           if (handler != null)
               handler(null, new PropertyChangedEventArgs(propName));
     }
}

And I am binding like this

var binding = new Binding("ShellWindow.ProgressbarVisibility") { Mode = BindingMode.TwoWay };
       progressbar = new CircularProgressBar ();
  progressbar.SetBinding(VisibilityProperty,
                             binding);

I think I am missing something, but I am not sure where I am wrong. Any help would be great.

The article says to use:

{Binding (local:Repository.Color)}

Since local: has no meaning outside a XAML file, I don't think it's possible to construct a binding with a string.

You can also assign a PropertyPath to the Binding.Path property, and this PropertyPath constructor accepts PropertyInfo . To use this constructor, the path string needs to be specified in tokenized format (described here ). Thus:

var propertyInfo = typeof(ShellWindow).GetProperty("ProgressbarVisibility");
var propertyPath = new PropertyPath("(0)", propertyInfo);
var binding = new Binding() { Path = propertyPath, Mode = BindingMode.TwoWay };

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