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

WPF Control Factory

Rate me:
Please Sign up or sign in to vote.
4.25/5 (7 votes)
20 Apr 2010CPOL6 min read 37.9K   418   16  
This article explains some advantages and disadvantages of factories, and shows one to use for generating WPF Controls.
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Threading;

namespace Pfz.WpfControls
{
	/// <summary>
	/// A control bound to a property of an object.
	/// </summary>
	/// <typeparam name="ObjectType">The type of the DataSource property.</typeparam>
	public class PropertyBoundControl<ObjectType>:
		PropertyBoundControlBase,
		IDataSourceChangedHandler,
		IIsReadOnlyChangedHandler
	{
		private ValueControl fValueControl = new ValueControl();
		
		/// <summary>
		/// Creates a new PropertyBoundControl instance.
		/// </summary>
		public PropertyBoundControl()
		{
			fValueControl.ValueChanged += p_ValueControl_ValueChanged;
			fValueControl.ValueChangeThrownException += p_ValueControl_ValueChangeThrownException;
			Content = fValueControl;
		}

		void p_ValueControl_ValueChangeThrownException(object sender, ValueExceptionEventArgs args)
		{
			args.RoutedEvent = ValueControl.ValueChangeThrownExceptionEvent;
			RaiseEvent(args);
		}

		private void p_ValueControl_ValueChanged(object sender, ValueChangedEventArgs args)
		{
			OnValueChanged(args);
		
			object value = Value;
			var binding = fPropertyBinding;
			if (binding == null)
				return;
			
			var property = binding.Property;
			if (property == null)
				return;
			
			var dataSource = DataSource;
			if (dataSource == null)
				return;
			
			if (p_IsReadOnly())
				return;
				
			property.SetValue(dataSource, value, null);
		}
		
		private PropertyBinding fPropertyBinding;
		
		/// <summary>
		/// Gets or sets the PropertyBinding of this control.
		/// </summary>
		public PropertyBinding PropertyBinding
		{
			get
			{
				return fPropertyBinding;
			}
			set
			{
				fPropertyBinding = value;
				p_MustRecreate();
			}
		}
		private bool fCanShowDisplayName = true;
		
		/// <summary>
		/// Gets or sets a value indicating is the DisplayName can be shown.
		/// </summary>
		[DefaultValue(true)]
		public bool CanShowDisplayName
		{
			get
			{
				return fCanShowDisplayName;
			}
			set
			{
				if (value == fCanShowDisplayName)
					return;

				fCanShowDisplayName = value;
				
				if (value)
				{
					var binding = fPropertyBinding;
					if (binding == null)
						fValueControl.DisplayName = null;
					else
						fValueControl.DisplayName = binding.ToString();
				}
				else
					fValueControl.DisplayName = null;
			}
		}
		
		/// <summary>
		/// Gets or sets the object that is read/written as the data-source.
		/// </summary>
		public ObjectType DataSource
		{
			get
			{
				var result = BoundControl.GetDataSource(this);
				if (!(result is ObjectType))
					return default(ObjectType);
				
				return (ObjectType)result;
			}
			set
			{
				BoundControl.SetDataSource(this, value);
			}
		}

		/// <summary>
		/// Gets or sets a value indicating if this control is/should-be read-only.
		/// </summary>
		public bool IsReadOnly
		{
			get
			{
				return BoundControl.GetIsReadOnly(this);
			}
			set
			{
				BoundControl.SetIsReadOnly(this, value);
			}
		}
		
		/// <summary>
		/// Gets or sets the value of this controls.
		/// </summary>
		public override object Value
		{
			get
			{
				return fValueControl.Value;
			}
			set
			{
				fValueControl.Value = value;
			}
		}
		
		/// <summary>
		/// Reads (refreshes) the value of the control from the data-source.
		/// </summary>
		public override void ReadFromDataSource()
		{
			var dataSource = DataSource;
			if (dataSource == null)
			{
				fValueControl.Clear();
				fValueControl.IsReadOnly = true;
				return;
			}
			
			fValueControl.IsReadOnly = p_IsReadOnly();
			fValueControl.Value = p_GetBoundValue();
		}

		private bool p_IsReadOnly()
		{
			var binding = fPropertyBinding;
			if (binding == null)
				return true;
			
			var property = binding.Property;
			if (property == null)
				return true;
			
			if (!property.CanWrite)
				return true;
				
			return IsReadOnly || BoundControl.IsDataSourceReadOnly(DataSource);
		}
		private object p_GetBoundValue()
		{
			var dataSource = DataSource;
			if (dataSource == null)
				return null;
			
			var binding = fPropertyBinding;
			if (binding == null)
				return null;
			
			var property = binding.Property;
			if (property == null)
				return null;
			
			return property.GetValue(dataSource, null);
		}
		
		private bool fMustRecreate;
		private void p_MustRecreate()
		{
			if (fMustRecreate)
				return;
			
			fMustRecreate = true;
			Dispatcher.BeginInvoke(new Action(p_RecreateNow));
		}
		private void p_RecreateNow()
		{
			fMustRecreate = false;
			
			var binding = fPropertyBinding;
			if (binding == null)
			{
				fValueControl.DataType = null;
				fValueControl.DisplayName = null;
				return;
			}
			
			if (fCanShowDisplayName)
				fValueControl.DisplayName = binding.ToString();
			else
				fValueControl.DisplayName = null;
				
			var property = binding.Property;
			if (property != null)
				fValueControl.DataType = property.PropertyType;
			
			ReadFromDataSource();
		}
		
		/// <summary>
		/// Method invoked when the value of this control changes.
		/// </summary>
		protected virtual void OnValueChanged(ValueChangedEventArgs args)
		{
			args.RoutedEvent = ValueControl.ValueChangedEvent;
			RaiseEvent(args);
		}
		
		/// <summary>
		/// Event invoked when the value of this control changes.
		/// </summary>
		public event EventHandler<ValueChangedEventArgs> ValueChanged
		{
			add
			{
				AddHandler(ValueControl.ValueChangedEvent, value);
			}
			remove
			{
				RemoveHandler(ValueControl.ValueChangedEvent, value);
			}
		}
		
		/// <summary>
		/// Event invoked when an exception is thrown during the process of 
		/// ValueChange.
		/// </summary>
		public event EventHandler<ValueExceptionEventArgs> ValueChangeThrownException
		{
			add
			{
				AddHandler(ValueControl.ValueChangeThrownExceptionEvent, value);
			}
			remove
			{
				RemoveHandler(ValueControl.ValueChangeThrownExceptionEvent, value);
			}
		}

		#region IDataSourceChangedHandler Members
			void IDataSourceChangedHandler.OnDataSourceChanged(DependencyPropertyChangedEventArgs args)
			{
				if (!fMustRecreate)
					ReadFromDataSource();
			}
		#endregion
		#region IIsReadOnlyChangedHandler Members
			void IIsReadOnlyChangedHandler.OnIsReadOnlyChanged(DependencyPropertyChangedEventArgs args)
			{
				fValueControl.IsReadOnly = p_IsReadOnly();
			}
		#endregion
	}
	
	/// <summary>
	/// A property-bound control that uses the DataSource as a System.Object.
	/// </summary>
	public sealed class ObjectPropertyBoundControl:
		PropertyBoundControl<object>
	{
	}
}

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 (Senior) Microsoft
United States United States
I started to program computers when I was 11 years old, as a hobbyist, 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 their 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, 2015 & 2016
Microsoft MVP 2013-2014 (in October 2014 I started working at Microsoft, so I can't be a Microsoft MVP anymore).

Comments and Discussions