2012-05-19

Articles

ObservableObject

 

The ObservableObject is the ideal base class for ViewModel objects, it just implements the INotifyPropertyChanged and provides a good method for sending the property change.

 

alt

 

Usage

namespace DW.SharpTools.Demo
{
	public class Item : ObservableObject
	{
		public Item(char value)
		{
			Value = value;
		}

		public char Value
		{
			get { return _value; }
			set
			{
				_value = value;
				NotifyPropertyChanged(() => Value);
			}
		}
		private char _value;
	}
}
<UserControl x:Class="DW.SharpTools.Demo.ObservableObjectControl"
			 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
			 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
			 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
			 xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
			 mc:Ignorable="d" 
			 d:DesignHeight="300" d:DesignWidth="300">
	<ListBox ItemsSource="{Binding Items}">
		<ListBox.ItemsPanel>
			<ItemsPanelTemplate>
				<WrapPanel />
			</ItemsPanelTemplate>
		</ListBox.ItemsPanel>
		<ListBox.ItemTemplate>
			<DataTemplate>
				<TextBlock Text="{Binding Value}" />
			</DataTemplate>
		</ListBox.ItemTemplate>
	</ListBox>
</UserControl>
using System.Linq;
using System.Windows.Controls;

namespace DW.SharpTools.Demo
{
	public partial class ObservableObjectControl : UserControl
	{
		public ObservableObjectControl()
		{
			InitializeComponent();
			DataContext = this;

			Items = new EnhancedObservableCollection<Item>();
			Items.AddRange(Enumerable.Range('a', 26).Select(i => new Item((char)i)));
		}

		public EnhancedObservableCollection<Item> Items { get; set; }
	}
}