Problems With BindingList<> part 3.

I have finally got the binding list down to a useful class plus an attribute.

This is not quite an attribute based approach but would be very useful for custom collections. 

DisplayNameAttribute is the useful meand of marking the column as being included. 

This would make a useful generic. 

My Fields string array sorts and filters the columns:

using System.Collections.Generic;
using System.ComponentModel;

namespace WindowsApplicationDataBinding
{
    public class Node
    {
        private string _Name;
        [DisplayName(“Full Name”)]
        public string Name{ get{return _Name;} set{_Name = Name;}}

        private int _Age;

        [DisplayName(“Age (years)”)]
        public int Age
        {
            get { return _Age; }
            set { _Age = value; }
        }

        public Node(string name, int age)
        {
            _Name = name;
            _Age = age;
        }
 

        // I don’t want this shown in the list

        public string Birthday { get { return “Unknown”; } }

    }
   
    public class BindingClass : BindingList<Node>, ITypedList
    {
        private string[] _Fields = new string[] {“Name”,”Age”};
       
        private PropertyDescriptorCollection _Description = null;

        #region ITypedList Members

        public PropertyDescriptorCollection GetItemProperties(PropertyDescriptor[] listAccessors)
        {
            if (_Description == null)
            {               
                // The default sort is alphabetical by field name.

               PropertyDescriptorCollection Temp =
                    TypeDescriptor.GetProperties(typeof(Node)).Sort(_Fields);
                _Description = new PropertyDescriptorCollection(null);
                foreach (PropertyDescriptor pd in Temp)
                {
                    foreach(string s in _Fields)
                    {
                        if (s == pd.Name)
                        {
                            _Description.Add(pd);
                        }
                    }
                }
               
            }
            return _Description;
        }

        public string GetListName(PropertyDescriptor[] listAccessors)
        {
            return typeof(Node).Name;
        }

        #endregion
    }
}

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s