我想将文本块文本绑定到静态类的属性。每当静态类的属性值更改时,它都应反映到另一个窗口或自定义控件上的文本块。
您可以使用x:Static标记扩展将其绑定到静态类的ANY属性,但是如果您不执行任何更改跟踪,则可能会导致刷新错误!
<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}}"/>