
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.
public static bool IsDictionary (Type type)
{
return (type.GetInterface ("IDictionary") != null
&& type != typeof(byte[]) && type != typeof(Image));
}
...
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).
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.
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..
public static Image ImageFromBase64 (string text)
{
try {
if (text == "")
return null;
byte[] memBytes = Convert.FromBase64String (text);
return ImageFromByte (memBytes);
} catch {
return null;
}
}
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.
public static void FormatXml (XmlNode owner, object value, string name, bool valueType)
{
if (value == null)
return;
Type type = value.GetType ();
if (TypeService.IsValueType (type) && !valueType) {
((XmlElement)owner).SetAttribute (name, Tool.TextFormat (value, "binary"));
} else if (CheckIFile && value is IFSerialize && !(owner is XmlDocument)) {
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 {
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)) {
IDictionary collection = value as IDictionary;
foreach (DictionaryEntry item in collection) {
FormatXml (element, item, "i", false);
}
} else if (TypeService.IsList (type)) {
IList collection = value as IList;
foreach (object item in collection)
FormatXml (element, item, "i", true);
} else{
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; }
}
...
public void Move (IPColumn moved, IPColumn destination, AnchorStyles anch, bool builGroup)
{
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;
mowner._Remove (moved);
if (mowner.Count == 0) {
mowner.Map._Remove (mowner);
}
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) {
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;
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
Localize.Load ();
Application.Run (new FormTest ());
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
Form f = new Form();DockControl c = new DockControl();ReachTextBox r = new ReachTextBox();
f.Controls.Add(c);
c.Add(r,DockType.Left);
Using PList
PList list = new PList();
list.DataSource = _listDataSource
list.AutoGenerateColumn = false;
list.AutoGenerateToString = true;
list.AutoGenerateToStringSort = true;
list.Info.HeaderVisible = false;
list.Info.ColumnsVisible = false;
list.Info.TreeMode = true;
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
- 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