Click here to Skip to main content
15,891,621 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.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using Pfz.WpfControls.BoundGridParts;

namespace Pfz.WpfControls
{
	/// <summary>
	/// Controls that displays many-records in a grid manner.
	/// </summary>
	public class ObjectBoundGrid<ObjectType>:
		UserControl
	{
		private HeaderPart fFixedRow = new HeaderPart();
		private RowDefinition fFixedRowDefinition = new RowDefinition();
		private ContentPart fContentGrid = new ContentPart();
		private ScrollViewer fScroller;
		private Canvas fCanvas;
		
		/// <summary>
		/// Creates a new grid.
		/// </summary>
		public ObjectBoundGrid()
		{
			var dockPanel = new DockPanel();
			dockPanel.LastChildFill = true;
			Content = dockPanel;
			
			var canvas = new Canvas();
			canvas.Children.Add(fFixedRow);
			fFixedRow.Height = fFixedRowHeight;
			canvas.Height = fFixedRowHeight;
			fCanvas = canvas;
			
			dockPanel.Children.Add(canvas);
			DockPanel.SetDock(canvas, Dock.Top);
			
			var scrollViewer = new ScrollViewer();
			scrollViewer.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;
			scrollViewer.VerticalScrollBarVisibility = ScrollBarVisibility.Visible;
			dockPanel.Children.Add(scrollViewer);
			scrollViewer.Content = fContentGrid;
			scrollViewer.ScrollChanged += scrollViewer_ScrollChanged;
			fScroller = scrollViewer;
			
			fFixedRow.RowDefinitions.Add(fFixedRowDefinition);

			fPropertyBindings.CollectionChanged += p_CollectionChanged;
			fValues.CollectionChanged += p_CollectionChanged;
		}

		void scrollViewer_ScrollChanged(object sender, ScrollChangedEventArgs e)
		{
			Canvas.SetLeft(fFixedRow, -e.HorizontalOffset);
		}

		/// <summary>
		/// Resizes the fixed row. I don't know which one is the best method to do
		/// such thing.
		/// </summary>
		protected override Size ArrangeOverride(Size arrangeBounds)
		{
			var result = base.ArrangeOverride(arrangeBounds);

			var sourceColumns = fContentGrid.ColumnDefinitions;
			var destColumns = fFixedRow.ColumnDefinitions;
			int count = Math.Min(sourceColumns.Count, destColumns.Count);
			for(int i=0; i<count; i++)
			{
				var sourceColumn = sourceColumns[i];
				var destColumn = destColumns[i];
				
				destColumn.Width = new GridLength(sourceColumn.ActualWidth);
			}
			
			fFixedRow.Width = fContentGrid.ActualWidth;
			
			return result;
		}

		/// <summary>
		/// Updated the vertical-scroll viewer height.
		/// </summary>
		protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo)
		{
			base.OnRenderSizeChanged(sizeInfo);

			double newHeight = sizeInfo.NewSize.Height - fFixedRowHeight;
			if (newHeight < 0)
				newHeight = 0;
			
			fScroller.Height = newHeight;
		}

		void p_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
		{
			p_RecreateContentNeeded();
		}
		
		private double fFixedRowHeight = 23;
		/// <summary>
		/// Gets or sets the height used by all rows.
		/// </summary>
		public double FixedRowHeight
		{
			get
			{
				return fFixedRowHeight;
			}
			set
			{
				if (value == fFixedRowHeight)
					return;
					
				fFixedRowHeight = value;
				fFixedRow.Height = value;
				fCanvas.Height = value;
			}
		}
		
		private ObservableCollection<GridPropertyBinding> fPropertyBindings = new ObservableCollection<GridPropertyBinding>();
		
		/// <summary>
		/// Gets or sets the property-bindings.
		/// </summary>
		[TypeConverter(typeof(GridPropertyBindingsTypeConverter))]
		public ObservableCollection<GridPropertyBinding> PropertyBindings
		{
			get
			{
				return fPropertyBindings;
			}
			set
			{
				if (value == fPropertyBindings)
					return;
					
				fPropertyBindings.Clear();
				if (value != null)
					foreach(var binding in value)
						fPropertyBindings.Add(binding);
			}
		}
		
		private ObservableCollection<ObjectType> fValues = new ObservableCollection<ObjectType>();
		/// <summary>
		/// Gets the records collection.
		/// </summary>
		[Browsable(false)]
		public ObservableCollection<ObjectType> Values
		{
			get
			{
				return fValues;
			}
		}
		
		private bool fRecreateContentNeeded;
		private void p_RecreateContentNeeded()
		{
			if (fRecreateContentNeeded)
				return;
			
			fRecreateContentNeeded = true;
			Dispatcher.BeginInvoke(new Action(p_RecreateContent));
		}
		private void p_RecreateContent()
		{
			fFixedRowDefinition.Height = new GridLength(1, GridUnitType.Auto);
		
			var propertyBindings = PropertyBindings;

			var fixedRowItems = fFixedRow.Children;
			var columns1 = fFixedRow.ColumnDefinitions;
			var columns2 = fContentGrid.ColumnDefinitions;
		
			fixedRowItems.Clear();
			columns1.Clear();
			columns2.Clear();
			
			int columnIndex = -1;
			foreach(var propertyBinding in propertyBindings)
			{
				columnIndex++;
			
				HeaderLabel label = new HeaderLabel();
				label.Content = propertyBinding.ToString();
				Grid.SetColumn(label, columnIndex);
				
				fixedRowItems.Add(label);
				
				var column1 = new ColumnDefinition();
				columns1.Add(column1);
				
				var column2 = new ColumnDefinition { Width = propertyBinding.Width };
				columns2.Add(column2);
			}
			
			columns1.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Auto) });
			
			var fakeItem = new HeaderLabel();
			Grid.SetColumn(fakeItem, columnIndex+1);
			fixedRowItems.Add(fakeItem);
			
			var rows = fContentGrid.Children;
			var rowDefinitions = fContentGrid.RowDefinitions;
			
			rows.Clear();
			rowDefinitions.Clear();
			
			int rowIndex = -1;
			foreach(var record in fValues)
			{
				rowIndex++;
				
				var rowDefinition = new RowDefinition();
				rowDefinitions.Add(rowDefinition);
				
				columnIndex = -1;
				foreach(var binding in propertyBindings)
				{
					columnIndex++;
					
					var control = new PropertyBoundControl<ObjectType>();
					control.CanShowDisplayName = false;
					control.PropertyBinding = binding;
					control.DataSource = record;
					
					Grid.SetColumn(control, columnIndex);
					Grid.SetRow(control, rowIndex);
					
					rows.Add(control);
				}
			}
			
			var lastRow = new RowDefinition { Height = new GridLength(0xEFFFFF, GridUnitType.Star) };
			rowDefinitions.Add(lastRow);
		}
	}
	
	/// <summary>
	/// Non-generic ObjectBoundGrid.
	/// Only exists because Xaml does not support generic controls.
	/// </summary>
	public sealed class ObjectBoundGrid:
		ObjectBoundGrid<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