我正在尝试将某个类的静态属性绑定到某个控件.我尝试了一些实现,但每个都有它的问题:
所有示例都使用下一个XAML:
<Label Name="label1" Content="{Binding Path=text}"/>
Run Code Online (Sandbox Code Playgroud)
第一种方法 - 不要使用INotifyPropertyChanged
public class foo1
{
public static string text { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
问题是,当'text'propery更改时,控件不会被通知.
第二种方法 - 使用INotifyPropertyChanged
public class foo1 : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
private static string _text;
public static string text
{
get { return _text; }
set
{
_text = value;
OnPropertyChanged("text");
}
}
}
Run Code Online (Sandbox Code Playgroud)
这不会编译,因为OnPropertyChanged()方法不是静态的,而是在静态方法中调用.
第二种方法尝试2:make OnPropertyChanged()方法static =>这不能编译,因为OnPropertyChanged()现在是静态的,并且它尝试使用非Property的'PropertyChanged'事件.
第二种方法尝试3:make'PropertyChanged'事件static =>这不会编译,因为该类没有实现'INotifyPropertyChanged.PropertyChanged'事件(该事件在'INotifyPropertyChanged接口中定义不是静态但在这里是静态的).
此时我放弃了.
有任何想法吗?