我想将文本块的文本绑定到静态类的属性。每当静态类的属性值更改时,应该反映在另一个窗口或自定义控件上的文本块中。
你可以使用 x:Static 标记扩展绑定到静态类上的任何属性,但如果它们没有实现任何更改跟踪,可能会在刷新时引发错误!
<TextBlock Text="{Binding Source={x:Static sys:Environment.MachineName}}" />
对于那些使用嵌套静态类来组织/区分常量的人。如果您需要绑定到嵌套静态类,则似乎需要使用加号(+)运算符而不是点(.)运算符来访问嵌套类:
{Binding Source={x:Static namespace:StaticClass+NestedStaticClasses.StaticVar}}
示例:
public static class StaticClass
{
public static class NestedStaticClasses
{
public static readonly int StaticVar= 0;
}
}
这对我有用:
Text="{Binding Source={x:Static MyNamespace:MyStaticClass.MyProperty}, Mode=OneWay}"
没有使用Mode=OneWay
我收到了一个异常。
它对我有用!
当您拥有像这样的静态属性的静态类时
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}}"/>
Source+x:Static
也不能启用通知,你必须使用Path
:<TextBlock Text="{Binding Path=(local:Foo.StaticBar)}"/>
。 - CodingNinja