Click here to Skip to main content
Click here to Skip to main content
Add your own
alternative version
Go to top

WPF Control Factory

, 20 Apr 2010
This article explains some advantages and disadvantages of factories, and shows one to use for generating WPF Controls.
WpfControlsAndSample.zip
WpfControlsAndSample
Pfz.ClassLibraries
Pfz
Caching
Collections
DataTypes
Extensions
Pfz.snk
Properties
Ranges
Threading
Pfz.WpfControls
BoundGridParts
Extensions
Pfz.WpfControls.snk
Properties
TypeConverters
WpfControlFactorySample
bin
Debug
Pfz.dll
Pfz.WpfControls.dll
WpfControlFactorySample.exe
Properties
Settings.settings
WpfControlFactorySample.suo
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Threading;
using Pfz.DataTypes;

namespace Pfz.WpfControls
{
	/// <summary>
	/// A control for editing values using the right editor for the data-type.
	/// </summary>
	public class ValueControl:
		UserControl,
		IValueControl,
		IHasDisplayName
	{
		/// <summary>
		/// RoutedEvent invoked when the value of this control changes.
		/// </summary>
		public static readonly RoutedEvent ValueChangedEvent =
			EventManager.RegisterRoutedEvent
			(
				"ValueChanged",
				RoutingStrategy.Direct,
				typeof(EventHandler<ValueChangedEventArgs>),
				typeof(ValueControl)
			);
			
		/// <summary>
		/// Event invoked when the change into the value of this control causes
		/// an error.
		/// </summary>
		public static readonly RoutedEvent ValueChangeThrownExceptionEvent = 
			EventManager.RegisterRoutedEvent
			(
				"ValueChangeThrownException",
				RoutingStrategy.Direct,
				typeof(EventHandler<ValueExceptionEventArgs>),
				typeof(ValueControl)
			);
	
		private IValueControl fInnerValueControl;
		
		private Type fDataType;
		/// <summary>
		/// Gets or sets the DataType used by this ValueControl.
		/// </summary>
		public TypeWrapper DataType
		{
			get
			{
				return fDataType;
			}
			set
			{
				fDataType = value;
				p_MustRecreate();
			}
		}
		
		private string fDisplayName;
		/// <summary>
		/// Gets or sets the displayname of the control.
		/// </summary>
		public string DisplayName
		{
			get
			{
				return fDisplayName;
			}
			set
			{
				fDisplayName = value;
				p_MustRecreate();
			}
		}
		
		private bool fMustRecreate;
		private void p_MustRecreate()
		{
			if (fMustRecreate)
				return;
			
			fMustRecreate = true;
			Dispatcher.BeginInvoke(new Action(p_DoRecreate));
		}
		private void p_DoRecreate()
		{
			if (!fMustRecreate)
				return;
			
			fMustRecreate = false;
			
			var dataType = fDataType;
			if (dataType == null)
			{
				Content = null;
				return;
			}
			
			var content = ControlFactory.TryCreate(dataType, fDisplayName);
			if (content != null)
			{
				fInnerValueControl = (IValueControl)content;
				
				if (fIsReadOnly)
					fInnerValueControl.IsReadOnly = true;
					
				IHasValueChanged hasValueChanged = content as IHasValueChanged;
				if (hasValueChanged != null)
					hasValueChanged.ValueChanged += p_ValueChanged;
			}
			else
			{
				content = new Label { Content = "There is not a registered editor for " + dataType.FullName + "." };
				fInnerValueControl = null;
			}
				
			Content = content;
		}

		object fOldValue;
		private void p_ValueChanged(object sender, RoutedEventArgs args)
		{
			p_CheckValueChanged();
		}
		private void p_CheckValueChanged()
		{
			object newValue;
			try
			{
				newValue = Value;
			}
			catch(Exception exception)
			{
				ValueExceptionEventArgs args = new ValueExceptionEventArgs();
				args.Exception = exception;
				
				OnValueChangeThrownException(args);
				if (args.Handled)
					return;
				
				if (args.Exception == null)
					return;
				
				if (args.Exception == exception)
					throw;
				
				throw args.Exception;
			}
			
			if (object.Equals(fOldValue, newValue))
				return;
			
			fOldValue = newValue;
			var args2 = new ValueChangedEventArgs();
			args2.WasChangedByUserAction = true;
			OnValueChanged(args2);
		}

		/// <summary>
		/// Method invoked when the processing os ValueChanged throws an exception.
		/// </summary>
		protected virtual void OnValueChangeThrownException(ValueExceptionEventArgs args)
		{
			args.RoutedEvent = ValueChangeThrownExceptionEvent;
			RaiseEvent(args);
		}

		/// <summary>
		/// Calls OnValueChanged if needed.
		/// </summary>
		protected override void OnLostKeyboardFocus(KeyboardFocusChangedEventArgs e)
		{
			base.OnLostKeyboardFocus(e);
			
			p_CheckValueChanged();
		}
		
		/// <summary>
		/// Invoked when the value changes, be it by user action or code.
		/// </summary>
		protected virtual void OnValueChanged(ValueChangedEventArgs args)
		{
			args.RoutedEvent = ValueChangedEvent;
			RaiseEvent(args);
		}
		
		/// <summary>
		/// Event invoked when the value is changed, be it by user action
		/// or code.
		/// </summary>
		public event EventHandler<ValueChangedEventArgs> ValueChanged
		{
			add
			{
				AddHandler(ValueChangedEvent, value);
			}
			remove
			{
				RemoveHandler(ValueChangedEvent, value);
			}
		}
		
		/// <summary>
		/// Event invoked when the ValueChange process throws an exception.
		/// </summary>
		public event EventHandler<ValueExceptionEventArgs> ValueChangeThrownException
		{
			add
			{
				AddHandler(ValueChangeThrownExceptionEvent, value);
			}
			remove
			{
				RemoveHandler(ValueChangeThrownExceptionEvent, value);
			}
		}

		#region IValueContainer Members
			/// <summary>
			/// Gets or sets the value of the control.
			/// </summary>
			public object Value
			{
				get
				{
					return fInnerValueControl.Value;
				}
				set
				{
					if (fMustRecreate)
					{
						Dispatcher.BeginInvoke(new Action<object>(p_SetValue), DispatcherPriority.DataBind, value);
						return;
					}
				
					p_SetValue(value);
				}
			}
			private void p_SetValue(object value)
			{
				var innerControl = fInnerValueControl;
				if (innerControl == null)
					return;
					
				innerControl.Value = value;
				
				// property is re-read, as between set and new get some difference
				// may exist.
				fOldValue = Value;
				
				var args = new ValueChangedEventArgs();
				OnValueChanged(args);
			}
		#endregion
		#region IValueControl Members
			/// <summary>
			/// Clears the value of this control.
			/// </summary>
			public void Clear()
			{
				if (fMustRecreate)
					Dispatcher.BeginInvoke(new Action(Clear), DispatcherPriority.DataBind);
				else
				if (fInnerValueControl != null)
					fInnerValueControl.Clear();
			}
			
			private bool fIsReadOnly;
			/// <summary>
			/// Gets or sets a value indicating if this control is/should be read-only.
			/// </summary>
			public bool IsReadOnly
			{
				get
				{
					return fIsReadOnly;
				}
				set
				{
					fIsReadOnly = value;
					
					if (fInnerValueControl != null)
						fInnerValueControl.IsReadOnly = value;
				}
			}
		#endregion
	}
}

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)

Share

About the Author

Paulo Zemek
Architect
Canada Canada
I started to program computers when I was 11 years old, as a hobbist, programming in AMOS Basic and Blitz Basic for Amiga.
At 12 I had my first try with assembler, but it was too difficult at the time. Then, in the same year, I learned C and, after learning C, I was finally able to learn assembler (for Motorola 680x0).
Not sure, but probably between 12 and 13, I started to learn C++. I always programmed "in an object oriented way", but using function pointers instead of virtual methods.
 
At 15 I started to learn Pascal at school and to use Delphi. At 16 I started my first internship (using Delphi). At 18 I started to work professionally using C++ and since then I've developed my programming skills as a professional developer in C++ and C#, generally creating libraries that help other developers do they work easier, faster and with less errors.
 
Want more info or simply want to contact me?
Take a look at: http://paulozemek.azurewebsites.net/
Or e-mail me at: paulozemek@outlook.com
 
Codeproject MVP 2012
Microsoft MVP 2013

| Advertise | Privacy | Mobile
Web01 | 2.8.140905.1 | Last Updated 20 Apr 2010
Article Copyright 2010 by Paulo Zemek
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid