如果您的数据源正在实现IList 接口,就像BindingList 所做的那样,则绑定正在尝试绑定到列表内元素的属性。
假设您有一个 string 项目列表,那么对于单个元素没有名为 Count 的属性。
将您的列表包装到一个委派Count 属性而不实现IList 接口的类,并在BindingList 触发ListChanged 事件时触发PropertyChanged 事件。
class CountWrapper : INotifyPropertyChanged
{
private readonly IBindingList bindingList;
public CountWrapper(IBindingList bindingList)
{
this.bindingList = bindingList;
bindingList.ListChanged += BindingList_ListChanged;
}
public event PropertyChangedEventHandler PropertyChanged;
public int Count
{
get { return bindingList.Count; }
}
private void BindingList_ListChanged(object sender, ListChangedEventArgs e)
{
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(string.Empty));
}
}
现在您可以像这样绑定Count 属性:
myLabel.DataBindings.Add("Text", new CountWrapper(myObjectList), "Count");
这对于其他属性也是可能的,只需为您的特定类使用特定的包装器。如果你的类为它自己的属性实现了INotifyPropertyChanged,你只需要监听那个事件并转发它。
class MyListWrapper : INotifyPropertyChanged
{
private readonly MyList bindingList;
public MyListWrapper(MyList bindingList)
{
this.bindingList = bindingList;
bindingList.ListChanged += BindingList_ListChanged;
bindingList.PropertyChanged+= BindingList_PropertyChanged;
}
public event PropertyChangedEventHandler PropertyChanged;
public int Count
{
get { return bindingList.Count; }
}
public int TotalCount
{
get { return bindingList.TotalCount; }
}
public string ReadWriteProperty
{
get { return bindingList.ReadWriteProperty; }
set { bindingList.ReadWriteProperty = value; }
}
private void OnPropertyChanged(PropertyChangedEventArgs ea)
{
var handler = PropertyChanged;
if (handler != null) handler(this, ea);
}
private void BindingList_ListChanged(object sender, ListChangedEventArgs e)
{
OnPropertyChanged(new PropertyChangedEventArgs(string.Empty));
}
private void BindingList_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
OnPropertyChanged(e);
}
}