在控件中实现绑定列表

时间:2010-07-12 13:01:58

标签: c# winforms data-binding binding user-controls

我在Winform上有一个(图像)用户控件..
我想将此Control绑定到绑定列表,以便每当(图像) 集合更改(显示在图像上)控件也会更改。 (应该反映集合中的图像) [类似于AsyncBinding List。]。

类似于.net控件如何使用DataSource属性。

// [EDITED]需要绑定列表。

    BindingList<Image> _images = GetImages("folder_path");   
    ImageControl ctrl = new ImageControl();   
    ctrl.DataSource = _images; //something similar

我怎样才能达到同样的目标?

EDIT2:
 基本上我想在列表中显示图像。类似于picasa显示它的东西。

image example http://www.aiostudents.com/images/articles/011_picasa3.jpg

全部谢谢

2 个答案:

答案 0 :(得分:1)

您需要使用BindingList,而不是List或Collection。关键的区别在于BindingList支持INotifyPropertyChanged,这是执行双向数据绑定所必需的。如果没有该接口,您最初可以绑定到列表,但对列表的更改不会反映在UI中。

答案 1 :(得分:1)

正如STW已经提到的那样,你需要一个BindingList<T>,这样列表中的变化就会传播到BindingSource。

下一步是如何通知您的UserControl有关BindingSource中的更改。要解决此问题,请将此代码添加为UserControl.cs的起点:

private BindingSource _DataSource;
[TypeConverter("System.Windows.Forms.Design.DataSourceConverter, System.Design")]
[Editor("System.Windows.Forms.Design.DataSourceListEditor, System.Design", typeof(UITypeEditor))]
[AttributeProvider(typeof(IListSource))]
public object DataSource
{
    get
    {
        return _DataSource;
    }
    set
    {
        //Detach from old DataSource
        if (_DataSource != null)
        {
            _DataSource.ListChanged -= _DataSource_ListChanged;
        }

        _DataSource = value as BindingSource;

        //Attach to new one
        if (_DataSource != null)
        {
            _DataSource.ListChanged += _DataSource_ListChanged;

            //ToDo: look for other (maybe usable) BindingSource events
            //http://msdn.microsoft.com/en-us/library/system.windows.forms.bindingsource_events.aspx
        }
    }
}

void _DataSource_ListChanged(object sender, ListChangedEventArgs e)
{
    //ToDo: Reacht on specific list change
    switch (e.ListChangedType)
    {
        case ListChangedType.ItemAdded:
            break;
        case ListChangedType.ItemChanged:
            break;
        case ListChangedType.ItemDeleted:
            break;
        case ListChangedType.ItemMoved:
            break;
        case ListChangedType.PropertyDescriptorAdded:
            break;
        case ListChangedType.PropertyDescriptorChanged:
            break;
        case ListChangedType.PropertyDescriptorDeleted:
            break;
        case ListChangedType.Reset:
            break;
        default:
            break;
    }
}

有了这个,你会被告知是否有人对BindingSource本身进行了更改(将整个列表与新的列表交换)或者附加到BindingSource的元素列表。

另外你应该对它进行测试,因为某些控件对列表的使用有点奇怪(例如,不要更改列表中的某些元素,清除它并从头开始填充它)。

也许this Walkthrough from Microsoft也可以提供帮助。我没看过,但看起来很有希望。