【发布时间】:2011-04-21 05:15:28
【问题描述】:
我想将文本块文本绑定到静态类的属性。每当静态类的属性值发生变化时,它应该反映到另一个窗口或自定义控件上的文本块。
【问题讨论】:
我想将文本块文本绑定到静态类的属性。每当静态类的属性值发生变化时,它应该反映到另一个窗口或自定义控件上的文本块。
【问题讨论】:
您可以使用x:Static 标记扩展绑定到静态类的任何属性,但如果您不实施任何更改跟踪,则可能会导致刷新错误!
<TextBlock Text="{Binding Source={x:Static sys:Environment.MachineName}}" />
【讨论】:
sender 参数?空?
对于那些使用嵌套静态类来组织/分离常量的人。如果您需要绑定到嵌套的静态类中,您似乎需要使用加号 (+) 运算符而不是点 (.) 运算符来访问嵌套类:
{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我得到了一个例外。
【讨论】:
xaml 设计器上的“无效标记”屏幕。奇怪的是,当我运行程序时它不会出错。不仅如此,显示错误的 sn-p 运行良好。知道是什么原因造成的吗?
它对我有用!
当你有像这样的静态属性的静态类时
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}}"/>
【讨论】: