在以下代码中:绑定到UIElement
的{{1}}在从集合中添加或删除项目时不会更新。
具体做法是:
Person对象包含ObservableCollection
属性Links,它可以包含任意数量的可以引用其他Person对象的Link对象。
Person和Link类都实现了ObservableCollection
接口。
INotifyPropertyChanged
Links和Crowd类都是ObservableCollections的子类。 Crowd对象是Person对象的ObservableCollection。 Links对象是Link对象的ObservableCollection:
public class Person: INotifyPropertyChanged
{
// INotifyPropertyChanged implementation
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
// fields
private string id = "";
private string firstName = "";
private string lastName = "";
private Links links = new Links();
// properties firing PropertyChanged events
public string ID
{
get { return id; }
set
{
if (value != this.id)
{
this.id = value;
NotifyPropertyChanged("ID");
}
}
}
public string FirstName
{
get { return firstName; }
set
{
if (value != this.firstName)
{
this.firstName = value;
NotifyPropertyChanged("FirstName");
}
}
}
public string LastName
{
get { return lastName; }
set
{
if (value != this.lastName)
{
this.lastName = value;
NotifyPropertyChanged("LastName");
}
}
}
public Links Links
{
get { return links; }
set
{
if (value != this.links)
{
this.links = value;
NotifyPropertyChanged("Links");
}
}
}
// constructors
public Person()
{
new Person("", "", "");
}
public Person(string id, string firstName, string lastName)
{
this.ID = id;
this.FirstName = firstName;
this.LastName = lastName;
}
}
public enum LinkState { none, oneway, twoway }
public class Link: INotifyPropertyChanged
{
// INotifyPropertyChanged implementation
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
// fields
private Person fromWhom;
private Person toWhom;
// properties firing PropertyChanged events
public Person FromWhom
{
get { return fromWhom; }
set
{
if (value != this.fromWhom)
{
this.fromWhom = value;
NotifyPropertyChanged("FromWhom");
}
}
}
public Person ToWhom
{
get { return toWhom; }
set
{
if (value != this.toWhom)
{
this.toWhom = value;
NotifyPropertyChanged("ToWhom");
}
}
}
// constructors
public Link()
{
new Link(null, null);
}
public Link(Person fromWhom, Person toWhom)
{
this.FromWhom = fromWhom;
this.ToWhom = toWhom;
}
}
WP7应用程序的MainPage类是PhoneApplicationPage类的子类。 它包含两个属性: 人群,群众对象和 我,一个Person对象。
以下XAML应显示: a)从Me对象到Crowd中的Person对象的链接数,以及 b)人群中Person对象的列表。
public class Links: ObservableCollection<Link>
{
}
public class Crowd : ObservableCollection<Person>
{
}
但是,当从Me.Links(ObserverableCollection)添加或删除Link对象时,名为“LinkCounter”的Textblock不会更新,即使它绑定到ObservableCollection。
由于Me.Links ObservableCollection在添加新链接时被更改,或者现有链接被删除,我认为绑定到它的任何内容都应该更新。
对此问题的任何帮助将不胜感激。 感谢。
答案 0 :(得分:0)
此处不会触发数据绑定,因为您没有更改对Links集合的引用。而不是绑定到引用并使用转换器尝试使用
<TextBlock x:Name=LinkCounter Text="{Binding ElementName=ThePage, Path=Me.Links.Count" />