在代码隐藏中绑定静态属性



我正在尝试遵循本文,唯一的区别是我在代码隐藏中创建和绑定控件。不幸的是,它不起作用。这是我的示例代码:

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

我像这样绑定

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

我想我错过了一些东西,但我不确定我错在哪里。任何帮助都会很棒。

文章说使用:

{Binding (local:Repository.Color)}

由于local:在 XAML 文件之外没有任何意义,因此我认为不可能使用字符串构造绑定。

还可以将 PropertyPath 分配给 Binding.Path 属性,此 PropertyPath 构造函数接受PropertyInfo 。若要使用此构造函数,需要以标记化格式指定路径字符串(此处所述)。因此:

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

最新更新