Click here to Skip to main content
Click here to Skip to main content

Controls Library: Extended ListView with Column Mapping

By , 29 Jan 2013
 

ctrlset/listedit.jpg

Edit properties/ sub properties

Introduction

A really easy and simple to use set of GUI classes for WinForms. It is written in 100% C# and does all the painting! This would enable us to work on tasks and not on how to present them in a form. This implies the ability to display and\or edit any object or collection with minimum preset and at the same time have all kinds and flexible configurations for developers and for end-users. 

Also alternative GUI version on Gtk . Implemented on Mono platform, using Gtk# and Gtk.net (pre alfa).  

The library contains a few bits and pieces of controls. Let us consider the generic list, for viewing and editing of collections. The first one needed is a set of tools to work with collections, runtime type information, localization, serialization, and related tasks.

Tools

Extended List

A special list that can improve performance and do several related tasks (filtering, indexing, change notification, custom sorting). 

Type Service  

You can slice work with System.Type, System.Reflection. And get custom attributes from System.ComponentModel.

//several methods from TypeService class
//check is specified type implement IDictionary interface
public static bool IsDictionary (Type type)
{
    return (type.GetInterface ("IDictionary") != null 
      && type != typeof(byte[]) && type != typeof(Image));
}
...
//check is specified property have [BrowAable(false/true)] attribute
public static bool GetBrowsable (PropertyInfo property)
{
    object[] dscArray = 
       property.GetCustomAttributes (typeof(BrowsableAttribute), false);
    if (dscArray.Length == 0)
        return true;
    return ((BrowsableAttribute)dscArray [0]).Browsable;
}
...

Reflection Access

Created for performance reasons (large collection sorting, get value of properties direct from paint event). Access through Reflection.PropertyInfo.Get/SetValue is much slower than direct access, but direct access can't give us flexibility. To eliminate this restriction, create a special wrapper: ReflectionAccessor which creates a dynamic method and delegates to this method, which significantly reduces the delay to appeal to the properties of objects. And create a static cache of created accessors. Works with FieldInfo, MethodInfo, PropertyInfo, and ConstructorInfo (in Test application, you can compare delays).

//return cached ctor accessor for specified type with specified parameters param
public static ReflectionAccessor InitCreateAccessor (Type type, Type[] param)
{
    if (cacheAccessors.Contains (type))
        return (ReflectionAccessor)cacheAccessors [type];
    ConstructorInfo ci = type.GetConstructor (param);
    if (ci == null)
        return null;
    ReflectionAccessor pa = new ReflectionAccessor (ci);
    cacheAccessors.Add (type, pa);
    return pa;
}

Localization System

A simple localization (that can be saved in a file and can be easily edited) user API is realized with only one static function Localize.Get("category", "name"). The code below localizes string CString and class LocalizeItem for storing Category (an example can be the name of a Form) and original Name. Fast data retrieval is implemented by the LocalizeItemList class by generating indexes for category and name.

//create index for value on LocalizeItemList class
public void AddIndex (string category, string name, LocalizeItem value)
{
    Dictionary<string, LocalizeItem > categoryIndex = null;
 
    if (index.ContainsKey (category))
        categoryIndex = index [category];
    else {
        categoryIndex = new Dictionary<string, LocalizeItem> ();
        index.Add (category, categoryIndex);
    }
    if (categoryIndex.ContainsKey (name))
        categoryIndex [name] = value;
    else {
        categoryIndex.Add (name, value);
    }    
}

Tools

Formatting and parsing byte[], images, date, etc., is done in ais.tool.Serialization..

//parse System.Drawing.Image from base64 from xml 
public static Image ImageFromBase64 (string text)
{
    try {
        if (text == "")
            return null;
        byte[] memBytes = Convert.FromBase64String (text);
        return ImageFromByte (memBytes);
    } catch {
        return null;
    }
}
//parse System.Drawing.Image from byte[]    
public static Image ImageFromByte (byte[] bytes)
{
    Image img = null;
    using (MemoryStream stream = new MemoryStream (bytes)) {
        img = Image.FromStream (stream);
    }
    return img;
}

Serialization

Targets fast and compact XML serialization of objects, using Tools and TypeService. For support class loader: use special type naming: Type.Name with Assembly.Name. Has special instructions for collection and dictionaries.  Supports DOM and SAX mode.

//format specified System.object value to specified XmlNode owner
public static void FormatXml (XmlNode owner, object value, string name, bool valueType)
{
    if (value == null)
        return;
    Type type = value.GetType ();
    //check type if is valuetype then serialize as XmlAttribute
    if (TypeService.IsValueType (type) && !valueType) {
        ((XmlElement)owner).SetAttribute (name, Tool.TextFormat (value, "binary"));
    } else if (CheckIFile && value is IFSerialize && !(owner is XmlDocument)) {
        //if implement IFileSerialize then serialize on separate file
        XmlElement element = (XmlElement)owner.AppendChild 
		(owner.OwnerDocument.CreateElement (name));
        IFSerialize ifl = value as IFSerialize;
        ifl.Save (Environment.CurrentDirectory);
        ((XmlElement)element).SetAttribute ("FileName", ifl.FileName);
    } else {
        //else create XmlElement and recursive write fields of object to node 
        XmlElement element = (XmlElement)owner.AppendChild (owner is XmlDocument ? 
          ((XmlDocument)owner).CreateElement (name) : 
		owner.OwnerDocument.CreateElement (name));
        if (valueType) {
            string typeName = type.FullName + ", " + type.Assembly.GetName ().Name;
            ((XmlElement)element).SetAttribute ("VT", typeName);
            if (TypeService.IsValueType (type))
                ((XmlElement)element).SetAttribute 
			(name, Tool.TextFormat (value, "binary"));
        }
        if (TypeService.IsDictionary (type)) {
            //special for dictionary
            IDictionary collection = value as IDictionary;
            foreach (DictionaryEntry item in collection) {
                FormatXml (element, item, "i", false);
            }
                 
        } else if (TypeService.IsList (type)) {
            ///special for list
            IList collection = value as IList;
            foreach (object item in collection)
                FormatXml (element, item, "i", true);
        } else{
            //write fields
            FieldInfo[] fields = TypeService.GetFields (type, true);
            foreach (FieldInfo field in fields) {
                object v = field.GetValue (value);
                if (TypeService.IsNonSerialized (field))
                    continue;
                if (!TypeService.CheckDefault (field, v)) {
                    FormatXml (element, v, field.Name, field.FieldType == 
                      typeof(object) || field.FieldType.IsInterface ? true : false);
                }
            } 
        }
    }
}

Controls 

Tool Form

To implement custom editing in list, ComboBox like controls. Supports: forms containing several open states and shows with alignment to calling control. Extended by ToolTipForm class to implement ToolTip like controls.  

Docked Windows

Primitive docking windows system, supports:

  • Dock any object derived from System.Windows.Form.Control
  • Left, right, top, bottom, and center content align
  • Mapped item layout 

Simple realization based on DockBox works like TabPage and uses MapLayout for aligning each box on a panel:  

public void OnSizeAllocated(Rectangle allocation)
{
    foreach (Panel p in sizePanel)
        p.Visible = false;
    List<ILayoutMapItem> list = LayoutMapTool.GetVisibleItems(map);
    map.GetBound(allocation.Width, allocation.Height);
    int i = 0;
    foreach (DockMapItem item in list)
    {
        Rectangle rect = map.GetBound(item);
        item.Panel.Bounds = rect;
        Panel spv = GetSizePanel(i);
        spv.Cursor = Cursors.VSplit;
        spv.BringToFront();
        spv.Tag = item;
        spv.Bounds = new Rectangle(rect.Right, rect.Top, 6, rect.Height);
        i++;
        Panel sph = GetSizePanel(i);
        sph.BringToFront();
        sph.Tag = item;
        sph.Cursor = Cursors.HSplit;
        sph.Bounds = new Rectangle(rect.Left, rect.Bottom, rect.Width, 6);
        i++;
    }
}

Control Service 

The primary task of this class is to paint all lists (columns, glyph, text, image) and related tasks.

public static void PaintGliph (Graphics graphics, Rectangle r, float angle)
{
	if (gliphTexture == null) {

		GraphicsPath gliphpath = new GraphicsPath ();
		gliphpath.AddLine (2, 8, 2, 4);
		gliphpath.AddLine (0, 4, 4, 0);
		gliphpath.AddLine (8, 4, 6, 4);
		gliphpath.AddLine (6, 8, 2, 8);
		gliphpath.CloseFigure ();

		Bitmap bmp = new Bitmap (8, 8);
		Graphics g = Graphics.FromImage (bmp);

		Brush gb = new SolidBrush (Color.Black);
				
		g.DrawPath (Pens.Black, gliphpath);
		gliphTexture = new TextureBrush (bmp, WrapMode.Clamp);

		g.FillPath (gb, gliphpath);
		gliphFillTexture = new TextureBrush (bmp, WrapMode.Clamp);
				
		gb.Dispose ();
		gliphpath.Dispose ();
		g.Dispose ();
	}
			
	gliphFillTexture.ResetTransform ();
	Matrix m = new Matrix ();
	if (angle != 0) {
		m.RotateAt (angle, new PointF (4, 4));
	}
	Matrix m2 = new Matrix ();
	m2.Translate (r.X, r.Y);
	gliphFillTexture.MultiplyTransform (m, MatrixOrder.Append);
	gliphFillTexture.MultiplyTransform (m2, MatrixOrder.Append);
	graphics.FillRectangle (gliphFillTexture, r);
}

List Viewer 

View list of any collection (alternative for ListView in detailed mode, DataGridView in virtual mode):

  • Inline properties (object.Property1.Property2...)
  • Universal, minimal configuration
  • Extended column manipulation (drag&drop, hide and size columns by mouse and context menu) 
  • Large collection support (grouping can slowdown)
  • Sorting. Grouping 
  • Serializable (PListInfo class easy to save and has all basic information about list)
  • Editing  

Column mapping realized by two classes that implement IPColumn:  PListColumn and PListColumnMap.

public interface IPColumn
{
    int Height { get; set; }

    int Width { get; set; }

    int RowIndex { get; set; }

    int ColIndex { get; set; }

    bool Visible { get; }

    string Property { get; }

    PListColumnMap Map { get; set; }
}
...
//moving specified column(moved) to specified side(anch) of other column(destination)
//inside the PListColumnMap
public void Move (IPColumn moved, IPColumn destination, AnchorStyles anch, bool builGroup)
{
    //check collision 
    if (moved.Map.Contains (destination) && 
           moved.Map != destination.Map && moved.Map.Map != null)
        return;
    if (moved.Map == destination.Map && destination.Map.Map != null)
        builGroup = false;

    PListColumnMap mowner = moved.Map;
    //remove from old map
    mowner._Remove (moved);
    //check map is empty
    if (mowner.Count == 0) {
        mowner.Map._Remove (mowner);
    }
    //check map is not empty but have only one item
    if (mowner != destination.Map && 
            mowner.Count == 1 && mowner.Map != null) {
         mowner.Map._Replace (mowner, mowner [0]);
    }
    if (destination.Map.Count == 1)
        builGroup = false;
        
     PListColumnMap owner = destination.Map;
     moved.RowIndex = destination.RowIndex;
     moved.ColIndex = destination.ColIndex;
     IPColumn column = moved;

     bool inserRow = false;
     if (builGroup) {
        //create new map
        PListColumnMap map = new PListColumnMap ();
        map.RowIndex = destination.RowIndex;
        map.ColIndex = destination.ColIndex;
            
        if (anch == AnchorStyles.Top) {
            map._Add (destination);
            map._Insert (moved, true);
        } else if (anch == AnchorStyles.Bottom) {
            map._Add (moved);
            map._Insert (destination, true);
        } else if (anch == AnchorStyles.Left) {
            map._Add (moved);
            map._Add (destination);
        } else if (anch == AnchorStyles.Right) {
            map._Add (destination);
            map._Add (moved);
        }
        column = map;
    } else {
        moved.RowIndex = destination.RowIndex;
        moved.ColIndex = destination.ColIndex;
        //move only by change indexes
        if (anch == AnchorStyles.Right)
            moved.ColIndex++;
        else if (anch == AnchorStyles.Top)
            inserRow = true;
        else if (anch == AnchorStyles.Bottom) {
            inserRow = true;
            moved.RowIndex++;
        }
    }
    owner._Insert (column, inserRow);
    TopMap.Info.OnBoundChanged (_cacheArg);
}

Properties Editor

  • Inline properties (object.Property1.Property2...)  
  • Sorting. Grouping. Hiding
  • Editing 
  • Printing  
  • Save configuration with reference to item type 

This mode is a state of PList. It simply creates a list of Fields from properties from the passed object and shows it in two columns: "Header" and "Value". And it has a third column "Group" used for grouping. 

public virtual object FieldSource
{
    get { return _fieldSource; }
    set
    {
        if (_fieldSource == value)
            return;

        OnCellEditEnd(new CancelEventArgs());
        INotifyPropertyChanged ip = _fieldSource as INotifyPropertyChanged;
        if (ip != null)
            ip.PropertyChanged -= _rowHandler;

        _fieldSource = value;

        if (_fieldSource == null)
        {
            SetNull();
            return;
        }

        Mode = PListMode.Fields;

        ip = _fieldSource as INotifyPropertyChanged;
        if (ip != null)
            ip.PropertyChanged += _rowHandler;

        FieldType = _fieldSource.GetType();

        QueueDraw(true);
    }
}
...

Tree View

This class overrides PList and sets it to tree mode. It simply uses a list of Nodes and shows it in filtered view; the filter checks if parents of a node are active (visible and expanded). 

public NodeInfo NodeInfo
{
    get
    {
        return nodeInfo;
    }
    set
    {
        if (nodeInfo == value)
            return;
        nodeInfo = value;
        ListExtendView<Node> view = nodeInfo.Nodes.DefaultView;
        view.Filter.Parameters.Clear();
        view.Filter.Parameters.Add(LogicType.Undefined, "ParentsExpand", CompareType.Equal, true);
        base.ListSource = view;
    }
}
... 

Background

This is planned as a universal controls library. The development was started on a database and documents flow projects.

It was a long way to implement my own control. Work started on a list view. The first step was a control based on DataGridView in Virtual mode, but it used too much memory. To avoid this, the second step was to derive from ListView, but lacked columns configuration and grouping in virtual mode. So when I had enough time and looked on CodeProject, I decided that it was possible. Hope this article helps everyone who wants to develop their own controls!

Many thanks to the entire CodeProject community. I take a lot of concepts, code from this site, and this article is the way in which I can bring it back.

Using the Code

Initialize Localization and List Information

// load data on startup 
Localize.Load ();
//or use
//Serialization.Load(Localize.Data, 
//  Path.Combine(Environment.CurrentDirectory, "localize.xml"))
Application.Run (new FormTest ());
//and save on exit
Localize.Save ();

Using Localize

public void Localizing ()
{
 this.button1.Text = Localize.Get ("Test", "List Editor");
 this.button2.Text = Localize.Get ("Test", "Test Reflection");
 this.button2.ToolTipText = Localize.Get ("Test", 
    "Test Reflection Accesor\nCompare properties access speed");
 this.button4.Text = Localize.Get ("Test", "Option Editor");
}

Using Docking Window

//initialize three controls
Form f = new Form();//main form
DockControl c = new DockControl();//container control
ReachTextBox r = new ReachTextBox();//simple editing control

//simple add it to your form
f.Controls.Add(c);

//and now add edit control to container, for example to left side
c.Add(r,DockType.Left);

Using PList

//to create list like System.Windows.Form.ListBox: 
PList list = new PList();
list.DataSource = _listDataSource
//now ready to use with all PList futures	    
//extended properties
list.AutoGenerateColumn = false;
list.AutoGenerateToString = true;
list.AutoGenerateToStringSort = true;
 //columns info
list.Info.HeaderVisible = false;
list.Info.ColumnsVisible = false;
list.Info.TreeMode = true;
//style setting            
list.StyleCell.Default.BorderColor = Color.Transparent;
list.StyleCell.Alter.BackColor = list.StyleCell.Default.BackColor;
list.StyleCell.Alter.BorderColor = list.StyleCell.Default.BorderColor;
 /custom properties 
list.SelectedItem = value;
...

History

  • 2011.09.16
    • First post
  • 2011.09.23
    • Default styles change 
    • Column editing (move, sizing highlighting and auto grouping)
    • Column context menu (allow adding sub columns and show hided columns)
    • Indexed properties
    • Selection by mouse
    • Inline sub properties for PList (like object.Prop1.Prop2...)
    • Support System.Data.DataView (ais.ctrl.PDataList)
    • Test for PDataList
  • 2011.10.05
    • Debug mostly
    • Styles (completely changed, allow save and edit by user, on each column)
    • ToolForm behavior on Windows (TODO: debug in mono)
    • CellEditorFont and CellEditorColor 
  • 2012.08.30
    • API changed
    • Merge PList and FList, add new properties ListSource and FieldSource
    • Add PTree it is like TreeView
    • Default styles, and styles system completely changed, compatibility serialization
    • Insert images cache to localization Localize.GetImage
    • Improve serialization performance
      • XmlWriter/Reader then XmlDocument, improve memory utilization 
      •  Dynamic method for fields access, improve speed  
      • Optimization for List item type, decrease file size
  • 2012.09.17
    • Scaling as internal option (Ctrl+Mouse Scroll)
    • Transparent Background 
    • List Editor filtering and improve Tree mode with ListExtendView<T> 
    • AutoSize overwrite GetPreferedSize  
  • 2013.01.02
    • Debug  
    • Gtk# version 
    • Text Diff in tools lib 
    • GroupBoxItem extending GroupBox 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

alexandrvslv
Kazakstan Kazakstan
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionMessage Automatically RemovedmemberMember 925812130 Aug '12 - 18:11 
QuestionCopyrighted images?memberjeffb4230 Aug '12 - 8:18 
AnswerRe: Copyrighted images?memberalexandrvslv30 Aug '12 - 17:53 
GeneralRe: Copyrighted images?memberjeffb424 Sep '12 - 6:45 
QuestionThank! New Source?memberMember 45586630 Aug '12 - 6:18 
AnswerRe: Thank! New Source?memberalexandrvslv30 Aug '12 - 18:22 
AnswerRe: Thank! New Source?memberalexandrvslv6 Sep '12 - 20:55 
GeneralThank you! This project is for Mono?memberMember 45586617 Sep '12 - 4:23 
GeneralRe: Thank you! This project is for Mono?memberalexandrvslv17 Sep '12 - 19:45 
GeneralRe: Thank! New Source?memberZac Greve1 Jan '13 - 16:41 
AnswerRe: Thank! New Source?memberalexandrvslv1 Jan '13 - 19:04 
GeneralRe: Thank! New Source?memberZac Greve1 Jan '13 - 19:23 
QuestionNew Version?memberMember 45586623 Aug '12 - 7:49 
AnswerRe: New Version?memberalexandrvslv23 Aug '12 - 8:07 
GeneralMy vote of 1memberToli Cuturicu24 Sep '11 - 3:29 
GeneralRe: My vote of 1memberalexandrvslv25 Sep '11 - 18:03 
GeneralRe: My vote of 1memberPaul Selormey25 Sep '11 - 18:16 
GeneralRe: My vote of 1memberToli Cuturicu25 Sep '11 - 22:14 
GeneralMy vote of 5memberPaul Selormey23 Sep '11 - 16:41 
GeneralRe: My vote of 5memberalexandrvslv25 Sep '11 - 18:06 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130513.1 | Last Updated 29 Jan 2013
Article Copyright 2011 by alexandrvslv
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid