Click here to Skip to main content
15,885,366 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.7K   418   16  
This article explains some advantages and disadvantages of factories, and shows one to use for generating WPF Controls.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;

namespace Pfz.WpfControls
{
	/// <summary>
	/// Controls that can be bound to a full record.
	/// </summary>
	public class ObjectBoundControl<ObjectType>:
		UserControl,
		IDataSourceChangedHandler,
		IIsReadOnlyChangedHandler
	{
		internal StackPanel fStackPanel;
		
		/// <summary>
		/// Creates a new RecordBoundControl.
		/// </summary>
		public ObjectBoundControl()
		{
			fStackPanel = new StackPanel();
			Content = fStackPanel;
			fPropertyBindings.CollectionChanged += fBoundProperties_CollectionChanged;
		}

		private bool fMustRecreate;
		void fBoundProperties_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
		{
			p_MustRecreate();
		}
		private void p_MustRecreate()
		{
			if (fMustRecreate)
				return;
			
			fStackPanel.Children.Clear();
			fMustRecreate = true;
			Dispatcher.BeginInvoke(new Action(p_RunMustRecreate));
		}
		private void p_RunMustRecreate()
		{
			if (!fMustRecreate)
				return;
				
			fMustRecreate = false;

			var children = fStackPanel.Children;
			children.Clear();
			
			var propertyBindings = fPropertyBindings;
			foreach(var propertyBinding in propertyBindings)
			{
				if (propertyBinding == null)
				{
					children.Add(new Separator());
					continue;
				}
				
				var control = new PropertyBoundControl<ObjectType>();
				control.PropertyBinding = propertyBinding;
				control.IsReadOnly = IsReadOnly;
				children.Add(control);
			}
			
			var args = new RoutedEventArgs(ObjectBoundControl.PropertyBoundControlsCreatedEvent);
			RaiseEvent(args);
		}
	
		/// <summary>
		/// Gets or sets the record to which this control is bound-to.
		/// </summary>
		[Browsable(false)]
		public ObjectType DataSource
		{
			get
			{
				object result = BoundControl.GetDataSource(this);
				if (result is ObjectType)
					return (ObjectType)result;
				
				return default(ObjectType);
			}
			set
			{
				BoundControl.SetDataSource(this, value);
			}
		}
		
		/// <summary>
		/// Gets or sets a value indicating if this control is read-only.
		/// </summary>
		[DefaultValue(false)]
		public bool IsReadOnly
		{
			get
			{
				return BoundControl.GetIsReadOnly(this);
			}
			set
			{
				BoundControl.SetIsReadOnly(this, value);
			}
		}
		
		private ObservableCollection<PropertyBinding> fPropertyBindings = new ObservableCollection<PropertyBinding>();
		
		/// <summary>
		/// Gets or sets the propeties this control will display.
		/// Example as string property:
		/// FullTypeName.* (which will get all properties)
		/// FullTypeName:PropertyName;OtherPropertyName
		/// FullTypeName:PropertyName=Display name;OtherPropertyName=Other display name
		/// FullTypeName.PropertyName=Display name;OtherFullTypeName.PropertyName=Other display name
		/// </summary>
		[TypeConverter(typeof(PropertyBindingsTypeConverter))]
		public ObservableCollection<PropertyBinding> PropertyBindings
		{
			get
			{
				return fPropertyBindings;
			}
			set
			{
				if (value == fPropertyBindings)
					return;
					
				fPropertyBindings.Clear();
				if (value != null)
					foreach(var item in value)
						fPropertyBindings.Add(item);
			}
		}

		private IEnumerable<PropertyBinding> p_AsBoundProperties(PropertyInfo[] propertyInfos)
		{
			foreach(var propertyInfo in propertyInfos)
				yield return new PropertyBinding { Property = propertyInfo };
		}

		/// <summary>
		/// Refreshes (re-reads) the data in all internal controls.
		/// </summary>
		public void RefreshData()
		{
			fRefreshDataNeeded = false;
			
			bool isReadOnly = IsReadOnly;
			foreach(var control in fStackPanel.Children)
			{
				var valueControl = control as PropertyBoundControl<ObjectType>;
				if (valueControl != null)
				{
					valueControl.IsReadOnly = isReadOnly;
					valueControl.ReadFromDataSource();
				}
			}
		}
		
		private bool fRefreshDataNeeded;
		private void p_RefreshDataNeeded()
		{
			if (fRefreshDataNeeded)
				return;
				
			fRefreshDataNeeded = true;
			Dispatcher.Invoke(new Action(RefreshData));
		}
		
		/// <summary>
		/// Event invoked whenever the child-controls are (re-)created.
		/// </summary>
		public event RoutedEventHandler PropertyBoundControlsCreated
		{
			add
			{
				AddHandler(ObjectBoundControl.PropertyBoundControlsCreatedEvent, value);
			}
			remove
			{
				RemoveHandler(ObjectBoundControl.PropertyBoundControlsCreatedEvent, value);
			}
		}
		
		#region IReadOnlyChangedHandler Members
			void IIsReadOnlyChangedHandler.OnIsReadOnlyChanged(DependencyPropertyChangedEventArgs args)
			{
				p_RefreshDataNeeded();
			}
		#endregion
		#region IDataSourceChangedHandler Members
			void IDataSourceChangedHandler.OnDataSourceChanged(DependencyPropertyChangedEventArgs args)
			{
				RefreshData();
			}
		#endregion
	}
	
	/// <summary>
	/// Non-generic version of ObjectBoundControl. It's here because
	/// Xaml does not support generic-classes and because the events
	/// are better registered only once, as non-generic.
	/// </summary>
	public sealed class ObjectBoundControl:
		ObjectBoundControl<object>
	{
		/// <summary>
		/// Event invoked when the ObjectBoundControl finishes creating all
		/// it's property-bound controls.
		/// </summary>
		public static readonly RoutedEvent PropertyBoundControlsCreatedEvent =
			EventManager.RegisterRoutedEvent
			(
				"PropertyBoundControlsCreated",
				RoutingStrategy.Direct,
				typeof(RoutedEventHandler),
				typeof(ObjectBoundControl)
			);
	}
}

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