代码改变世界

在winform开发中,将集合类型(ArrayList)邦定到控件上,实现集合与控件中显示的数据同步

2005-06-28 10:56  netwy  阅读(2901)  评论(4编辑  收藏  举报

在进行winform的开发中,难免碰上将一个集合类型的数据邦定到控件(ListBox、DataGrid等)上,当
集合中的数据发生变化时,控件中显示的数据不能自动更新,下面是我在msdn上找到的:

如果绑定到没有实现 IBindingList 接口的数据源(如 ArrayList 对象),则在更新数据源时,
将不会更新绑定控件的数据。例如,如果将组合框绑定到 ArrayList 对象并将数据添加到 ArrayList 中,
则这些新项将不会出现在组合框中。但是,您可以通过调用控件绑定到的 BindingContext 类的实例上的 SuspendBinding
和 ResumeBinding 方法强制更新组合框。

下面是我做的例子:
Wellknown类:

        public class Wellknown
    {
        
        
private string _mode;
        [XmlAttribute(
"mode")]
        
public string Mode
        {
            
get{return _mode;}
            
set{_mode=value;}
        }
        
private string _type;
        [XmlAttribute(
"type")]
        
public string Type
        {
            
get{return _type;}
            
set{_type=value;}
        }
        
private string _objectUri;
        [XmlAttribute(
"objectUri")]
        
public string ObjectUri
        {
            
get{return _objectUri;}
            
set{_objectUri=value;}
        }
    }
集合类:
public class WellknownArrayList:ArrayList
    {
        
        
public int Add(Wellknown value)
        {
            
return base.Add(value);
        }

        
public new Wellknown this[int index]
        {
            
get
            {
                
return (Wellknown)base[index];
            }
            
set
            {
                
base[index]=value;
            }
        }
        
public override int Count
        {
            
get
            {
                
return base.Count;
            }
        }
    }

应用程序:
        邦定数据源:  
                     listBox1.DataSource=arr;//arr集合变量,里面存储Wellknown对象
                     listBox1.DisplayMember="ObjectUri";
                     listBox1.ValueMember="ObjectUri";  
         给arr添加Wellknown对象,并更新listBox1控件:
                    Wellknown w=new Wellknown();
                     w.Mode=this.ActiveType;
                     w.Type=type+","+assemblyName;
                     w.ObjectUri=name[name.Length-1];
                     listBox1.BindingContext[arr].SuspendBinding();
                     arr.Add(w);
                     listBox1.BindingContext[arr].ResumeBinding();  
这样,listBox1控件的数据显示自动更新