绑定到静态类属性[重复]

问题描述 投票:50回答:4

我想将文本块文本绑定到静态类的属性。每当静态类的属性值更改时,它都应反映到另一个窗口或自定义控件上的文本块。

c# wpf binding textblock
4个回答
74
投票

您可以使用x:Static标记扩展将其绑定到静态类的ANY属性,但是如果您不执行任何更改跟踪,则可能会导致刷新错误!

<TextBlock Text="{Binding Source={x:Static sys:Environment.MachineName}}" />

21
投票

对于那些使用嵌套静态类来组织/分隔常量的人。如果需要绑定到嵌套的静态类中,似乎需要使用加号(+)运算符而不是点(。)运算符来访问嵌套类:

{Binding Source={x:Static namespace:StaticClass+NestedStaticClasses.StaticVar}}

示例:

public static class StaticClass
    {
        public static class NestedStaticClasses
        {
            public static readonly int StaticVar= 0;

        }
    }

18
投票

这对我有用:

Text="{Binding Source={x:Static MyNamespace:MyStaticClass.MyProperty}, Mode=OneWay}"

没有Mode=OneWay,我有一个例外。


-1
投票

对我有用!

当您具有带有此类静态属性的静态类时

 namespace App.Classes
 {
     public static class AppData
     {
         private static ConfigModel _configModel;
         public static ConfigModel Configuration
         {
            get { return _configModel; }
            set { _configModel = value; }
         }
     }

     public class ConfigModel : INotifyPropertyChanged
     {
         public event PropertyChangedEventHandler PropertyChanged;

          private bool _text = true;
          public bool Text
          {
               get { return _text ; }
               set { 
                     _text = value; 
                     PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Text"));
               }
          }
      }
}

您可以像这样将其绑定到xaml。

xmlns:c="clr-namespace:App.Classes"

<TextBlock Text="{Binding Path=Text, Source={x:Static c:AppData.Configuration}}"/>
© www.soinside.com 2019 - 2024. All rights reserved.