WPF怎样绑定一个从ObservableCollection<T>继承的集合对象?
比如
class MyClass : ObservableCollection <EmployeeInfo>
{
...
}
MyClass cls = new MyClass();
数据填充完毕后...
this.DataContext = cls;
xaml里
<TextBlock Text= "{Binding Path=XXX} " />
TextBlock里不显示数据。为什么?或者说应该怎样写.
------解决方案--------------------试了,没问题。
// Class1.cs
class Class1 : System.ComponentModel.INotifyPropertyChanged
{
private string name;
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
public string Name
{
get { return name; }
set {
name = value;
OnPropertyChanged( "Name ");
}
}
private int age;
public int Age
{
get { return age; }
set {
age = value;
OnPropertyChanged( "Age ");
}
}
private void OnPropertyChanged(string strProperty)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(strProperty));
}
}
public Class1(string name, int age)
{
this.name = name;
this.age = age;
}
}
// Class2.cs
class Class2 : System.Collections.ObjectModel.ObservableCollection <Class1>
{
public Class2()
{
Add(new Class1( "name1 ", 1));
Add(new Class1( "name2 ", 2));
Add(new Class1( "name3 ", 3));
Add(new Class1( "name4 ", 4));
Add(new Class1( "name5 ", 5));
}
}
======
从Expression Blend打开这个项目,在Project标签下点击+CLR Object,选择Class2,然后把Class2拖到Window界面上,提示用什么表示数据,可以选择ListBox...
然后,右键选择生成的ListBox, 'Edit Other Templates '-> 'Edit Generated Items '-> 'Edit Template '做一些格式化操作。
当然,在Expression Blend上的操作可以省掉,直接new一个Collection,然后指定DataContext.