Click here to Skip to main content
15,891,529 members
Articles / Desktop Programming / WPF

ObjectPresenter - How to Generate an Object's Testing GUI from a Given Object

Rate me:
Please Sign up or sign in to vote.
4.94/5 (27 votes)
5 Jan 2012CPOL11 min read 37.4K   924   49  
In this article, I explain step by step, how we can create a WPF custom control that gets an object and, generates a GUI that enables editing that object's properties and invoking that object's methods.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace ObjectPresentation
{
    public class FieldInputValueViewModel : InputValueViewModel
    {
        #region Constructors
        public FieldInputValueViewModel(FieldInfo fi)
            : this(fi, 0)
        {
        }

        public FieldInputValueViewModel(FieldInfo fi, int valueLevel)
        {
            ValueLevel = valueLevel;
            FieldInformation = fi;
        }
        #endregion

        #region Properties

        #region FieldInformation
        private FieldInfo _fieldInformation;
        public FieldInfo FieldInformation
        {
            protected get { return _fieldInformation; }
            set
            {
                if (_fieldInformation != value)
                {
                    FieldInfo oldValue = _fieldInformation;
                    _fieldInformation = value;
                    OnFieldInformationChanged(oldValue, _fieldInformation);
                }
            }
        }

        protected virtual void OnFieldInformationChanged(FieldInfo oldValue, FieldInfo newValue)
        {
            if (newValue == null)
            {
                return;
            }

            Name = newValue.Name;
            ValueType = newValue.FieldType;            
        }
        #endregion

        #endregion

        protected override void SetObjectFieldValue(object o)
        {
            if (o == null)
            {
                return;
            }

            Type objectType = o.GetType();
            FieldInfo objectField = objectType.GetField(Name);

            try
            {
                objectField.SetValue(o, GetValue());
            }
            catch (Exception ex)
            {
            }
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

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


Written By
Software Developer
Israel Israel
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions