我想将文本块文本绑定到静态类的属性。只要静态类的属性值发生变化,它就应该反映到另一个窗口或自定义控件上的文本块。
答案 0 :(得分:67)
您可以使用x:Static标记扩展名绑定到静态类的任何属性,但如果您没有实现任何更改跟踪,则可能会导致刷新错误!
<TextBlock Text="{Binding Source={x:Static sys:Environment.MachineName}}" />
答案 1 :(得分:18)
这对我有用:
Text="{Binding Source={x:Static MyNamespace:MyStaticClass.MyProperty}, Mode=OneWay}"
没有Mode=OneWay
我有例外。
答案 2 :(得分:17)
对于那些使用嵌套静态类来组织/分离常量的人。如果需要绑定到嵌套的静态类中,似乎需要使用加号(+)运算符而不是点(。)运算符来访问嵌套类:
{Binding Source={x:Static namespace:StaticClass+NestedStaticClasses.StaticVar}}
示例:
public static class StaticClass
{
public static class NestedStaticClasses
{
public static readonly int StaticVar= 0;
}
}
答案 3 :(得分:-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}}"/>