dan*_*ana 4 data-binding wpf inotifypropertychanged
我正在尝试将某个类的静态属性绑定到某个控件.我尝试了一些实现,但每个都有它的问题:
所有示例都使用下一个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接口中定义不是静态但在这里是静态的).
此时我放弃了.
有任何想法吗?
H.B*_*.B. 11
我建议你只需要一个instance-property返回你的静态属性,如下所示:
private static string _text;
public string text
{
get { return _text; }
set
{
_text = value;
OnPropertyChanged("text");
}
}
Run Code Online (Sandbox Code Playgroud)
然而,这使得整个绑定相对毫无意义,因为更改通知仅在类的一个实例中创建,而不是在每个实例中创建.因此,只有绑定到更改它的特定实例上的属性的绑定才会更新.
如这里可以看到的更好的方法是使用单例.
| 归档时间: |
|
| 查看次数: |
12454 次 |
| 最近记录: |