Infragistics ASP.NET controls

C# 5.0: INotifyPropertyChanged with the [CallerMemberName] attribute

WPF/Silverlight and the INotifyPropertyChanged interface Greetings and welcome to another post on refactorthis.net. Today's topic is about an interface that all WPF and Silverlight developers have grown to love.  The INotifyPropertyChanged interface facilitates notifying the data binding mechanisms of WPF and Silverlight of a property value change in your ViewModel to your view.  Here is a simple illustration.   ClassicViewModel.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace INotifyPropertyChangedExample { public class ClassicViewModel { private string _personName; public event PropertyChangedEventHandler PropertyChanged; public string PersonName { get; set { if (value != _personName) _personName = value; //No type safety here. If you make a mistake you will have problems. OnPropertyChanged("PersonName"); } } public void OnPropertyChanged(string property) { if (property == null) throw new ArgumentNullException("property"); if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(property)); } } } When calling the method to raise the property changed event, you would need to pass the property name as a string to the handler.  If you made any mistake in typing the property name, you would have to take time to debug your data binding. A new and improved solution C# 5.0 has provided some nifty compiler level attributes to assist with this scenario. The [CallerMemberName] attribute of the System.Runtime.CompilerServices namespace can be used as an optional method parameter.  When a method is called and there is no value specified for the parameter that is decorated with this attribute, you are provided with the name of the member that called the method.  This takes the risk of a typing mishap out of your hands and allows you to rely on the compiler to provide this information to you!  Here is an updated example! ImprovedViewModel.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; namespace INotifyPropertyChangedExample { public class ImprovedViewModel : INotifyPropertyChanged { private string _personName; public event PropertyChangedEventHandler PropertyChanged; public string PersonName { get { return _personName; } set { if (value != _personName) _personName = value; OnPropertyChanged(); } } public void OnPropertyChanged([CallerMemberName] string property = null) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(property)); } } }   As you can see, this is a great little addition to the C# language that will make your life a little easier. I'd like to thank Patrick Steel for his article in MSDN magazine that inspired this article.  Please check out his article for more uses of this and other new attributes and features of the C# 5.0 language. http://visualstudiomagazine.com/Articles/2012/11/01/More-Than-Just-Async.aspx kick it on DotNetKicks.com


Implementing a re-sizable composite view user interface using the MVVM pattern, the GridSplitter, and WPF UserControls.

  A composite view user interface In the world of WPF, the Model-View-ViewModel pattern is a great way to separate your UI from your business logic.  This decoupling allows you to easily unit test your code.  When implemented correctly, the MVVM pattern promotes a view agnostic structure which makes switching between different views extremely easy.  A composite view UI is basically a user interface that is made up of multiple independent views.  By independent, I mean that the views should be decoupled and unaware of each other.  In this tutorial, I will show you how to create the following UI.     Existing frameworks There are several existing frameworks that facilitate the implementation of the MVVM pattern and composite view applications.  MVVM Toolkit, MvvMLight, SoPrism, and Prism are a few examples of some of the existing libraries out there.  Prism is probably the most complete and extensive but it also has a large learning curve.  I decided that before I dive into learning the details of Prism, I would benefit by trying to code a composite application by hand.  The User Interface design The previous screen shot shows an application made up of a Window that contains a grid, a listview, and a ContentControl.  The ContentControl and ListView are separated by a GridSplitter control.  This allows the two views to be re-sized.  The ContentControl will have a UserControl injected into the content property as the ListView's selected item is changed. Here is the XAML markup <Window x:Class="OutlookLayoutPresenter.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:views="clr-namespace:OutlookLayoutPresenter.Views" Title="MainWindow" Height="350" Width="525"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="128*" /> <ColumnDefinition Width="375*" /> </Grid.ColumnDefinitions> <ListView SelectionChanged="lstMenu_SelectionChanged" IsSynchronizedWithCurrentItem="True" DisplayMemberPath="MenuDisplayText" x:Name="lstMenu"> </ListView> <ContentControl Grid.Column="1" Content="{Binding Path=Presenter.CurrentView}" x:Name="MainContent"> </ContentControl> <GridSplitter Grid.Column="1" Width="2" HorizontalAlignment="Left" /> </Grid> </Window> As you can see, we have a Grid with two columns.  The column on the left holds a ListView that that is data bound in the code behind.  The ContentControl's content property is also data bound to the Presenter.CurrentView property of our ViewModel.  I chose to implement a presenter object to handle the injection of the UserControl into the ContentControl.  We will start with the codebehind of our view to show how we are setting the DataContext. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using OutlookLayoutPresenter.Views; namespace OutlookLayoutPresenter { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { private MainWindowViewModel _viewModel; public MainWindow() { InitializeComponent(); _viewModel = new MainWindowViewModel(); this.DataContext = _viewModel; lstMenu.ItemsSource = _viewModel; } void lstMenu_SelectionChanged(object sender, SelectionChangedEventArgs e) { var menuItem = (ViewMenuItems)e.AddedItems[0]; _viewModel.Presenter.DisplayView(menuItem); } } } Note that we have bound our ViewModel to the view's DataContext as well as the ListView's ItemsSource property.  The ViewModel is an ObservableCollection of ViewMenuItem objects.  I created the ViewMenuItem class to contain the region's name and the display text.  The ListView serves as a menu.   Here is the code for the ViewMenuItem class. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; namespace OutlookLayoutPresenter { public class ViewMenuItems : INotifyPropertyChanged { private string _regionName; private string _menuDisplayText; public string RegionName { get { return _regionName; } set { if (_regionName == value) return; _regionName = value; OnPropertyChanged("RegionName"); } } public string MenuDisplayText { get { return _menuDisplayText; } set { if (_menuDisplayText == value) return; _menuDisplayText = value; OnPropertyChanged("MenuDisplayText"); } } public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propertyName) { var handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } } } When looking at the ViewModel, please be sure to note the public Presenter property that is used in the data binding of the ContentControl. The ObservableCollection of ViewMenuItem objects builds the ListView menu. Here's the ViewModel's code using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; using System.Collections.ObjectModel; namespace OutlookLayoutPresenter { public class MainWindowViewModel : ObservableCollection<ViewMenuItems> , INotifyPropertyChanged { private IPresenter _presenter; public IPresenter Presenter { get { return _presenter; } set { _presenter = value; OnPropertyChanged("Presenter"); } } public MainWindowViewModel () { this.Add(new ViewMenuItems{RegionName = "RegionOne", MenuDisplayText = "Content One"}); this.Add(new ViewMenuItems{RegionName = "RegionTwo", MenuDisplayText = "Content Two"}); this.Add(new ViewMenuItems{RegionName = "RegionThree", MenuDisplayText = "Content Three"}); this.Presenter = new MainWindowPresenter(); } public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propertyName) { var handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } } } All that's left now is the MainWindowPresenter class which will dynamically load one of three user controls based on the ListView's selected item. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; using System.Windows.Controls; using OutlookLayoutPresenter.Views; namespace OutlookLayoutPresenter { /// <summary> /// This is the presenter class for the main Shell. the purpose of this /// class is to contain all of the UI event handlers for the main shell view. /// </summary> public class MainWindowPresenter : INotifyPropertyChanged, IPresenter { ContentControl _currentView = new ContentControl(); public ContentControl CurrentView { get { return _currentView; } set { _currentView = value; OnPropertyChanged("CurrentView"); } } public void DisplayView(ViewMenuItems item) { switch (item.RegionName.ToUpper()) { case "REGIONONE": this.CurrentView.Content = new ContentOne(); break; case"REGIONTWO": this.CurrentView.Content = new ContentTwo(); break; case "REGIONTHREE": this.CurrentView.Content = new ContentThree(); break; } } public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propertyName) { var handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } } } There are three user controls that have a different background color and text.  I will show the markup for one of the controls for brevity. <UserControl x:Class="OutlookLayoutPresenter.Views.ContentOne" 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" Background="Blue"> <Grid> <TextBlock FontWeight="Bold" Foreground="White" Text="Content One" /> </Grid> </UserControl>   As you click on each menu item, the content view will change colors and text.  I've included the source code for your reference. OutlookLayoutPresenterMVVM.zip (93.27 kb)   This concludes the tutorial.  Thanks for reading! Until next time... Buddy James kick it on DotNetKicks.com      


How to list local Windows System Services and their dependencies using WPF DataBinding and MVVM

The example I wrote this example in an effort to monitor the Windows Services that are installed on my system at any given time.  I decided to kill two birds with one stone and learn a bit about MVVM, DataBinding, and WPF in the process.  I'll start by showing you a class diagram of the solution.  I'll follow with providing all of the source code snippets for your review.  Finally, I'll explain the application and provide a link for you to download the complete solution. Malware and Windows Services I've learned that Malware as well as viruses often disguise themselves as "normal" Windows services to take advantage of automatic/delayed starting capabilities.  Windows services are also an ideal place for degenerates to place their malicious code because most of your typical Windows users don't take a second look here for problems. Windows Services And here is a screen shot of the application that I wrote to explore the many facets of WPF databinding. As you can see, the application simply lists all Windows service names, Display names, and their dependent services.  The goal was to perform a google search when double clicking a service (you can add this if you like, it's probably about 3 lines of code).  I thought I could easily google suspicious looking services to find any problematic applications.  The ServiceController[] array The .NET framework class library contains an object that describes a Windows Service and it's called the ServiceController.  I decided that I would create a wrapper around this ServiceContoller array with my own object so that I could implement ObservableCollection<> as well as INotifyPropertyChanged to make the collection of objects play nice with WPF's DataBinding.  Here is a class diagram that illustrates the entire application.                   And here's the code.... WindowsService.cs (a wrapper to ServiceController) using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Text; namespace WindowsServiceMonitor { /// <summary> /// The purpose of this class is to serve as a wrapper class to the /// ServiceController. This class provides propertychange notification /// to allow databinding with WPF. /// </summary> public class WindowsService : INotifyPropertyChanged { #region "private members" private string _serviceName; private string _displayName; private WindowsServiceCollection _dependentServices; #endregion #region "INotifyPropertyChanged event" /// <summary> /// Facilities property change notification and WPF databinding /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// This method is called when any property is changed /// </summary> /// <param name="info"></param> protected void OnPropertyChanged(string info) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(info)); } } #endregion #region "Public constructors" /// <summary> /// Overloaded constructor /// </summary> /// <param name="serviceName">The short name of the service</param> /// <param name="displayName">The friendly display name of the service</param> /// <param name="dependentServices">An observable collection of windows services</param> public WindowsService(string serviceName, string displayName, WindowsServiceCollection dependentServices) { _serviceName = serviceName; _displayName = displayName; _dependentServices = dependentServices; } /// <summary> /// Default constructor /// </summary> public WindowsService() { } #endregion #region "Public Properties" /// <summary> /// The short name of the service /// </summary> public string ServiceName { get { return _serviceName; } set { _serviceName = value; OnPropertyChanged("ServiceName"); } } /// <summary> /// The friendly display name of the service /// </summary> public string DisplayName { get { return _displayName; } set { _displayName = value; OnPropertyChanged("DisplayName"); } } /// <summary> /// An observable collection of windows services /// </summary> public WindowsServiceCollection DependentServices { get { return _dependentServices; } set { _dependentServices = value; OnPropertyChanged("DependentServices"); } } /// <summary> /// override the object tostring method to return the service name /// </summary> /// <returns></returns> public override string ToString() { return _serviceName; } #endregion } } WindowsServiceCollection.cs (A wrapper to ServiceController[] which inherits ObservableCollection<>) using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.ServiceProcess; using System.Text; namespace WindowsServiceMonitor { /// <summary> /// A WPF friendly collection of WindowsService objects /// </summary> public class WindowsServiceCollection : ObservableCollection<WindowsService> { /// <summary> /// Default constructor /// </summary> public WindowsServiceCollection() : base() { } /// <summary> /// Add all windows services to this collection object /// </summary> /// <param name="windowsServices">The current windows service</param> public void LoadServices(ServiceController[] windowsServices) { try { //loop through each root level service dependency foreach (ServiceController service in windowsServices) { //create a new WPF friendly windows service object WindowsService windowsService; windowsService = new WindowsService(); //Set the service properties windowsService.ServiceName = service.ServiceName; windowsService.DisplayName = service.DisplayName; try { //recursivley build the service depdencies WindowsServiceCollection.BuildDependentServiceHierarchy(windowsService, service.DependentServices); } catch (InvalidOperationException exception) { //I've received unable to open ___ service on the computer //I'll use an empty catch until i research the issue. var operationExceptionMessage = exception.Message; } catch (Exception exception) { var generalExceptionMessage = exception.Message; } //add the WPF friendly service to this Observable service collection Add(windowsService); } } catch (Exception ex) { var message = ex.Message; } } /// <summary> /// recursivley build the service depdencies /// </summary> /// <param name="service">the WFP friendly windows service wrapper</param> /// <param name="dependentServices">The collection of windows service dependencies</param> /// <returns></returns> public static void BuildDependentServiceHierarchy(WindowsService service, ServiceController[] dependentServices) { //if we don't have a valid service object if (service == null) //alert the caller throw new NullReferenceException("Invalid service object."); //loop through each dependent service foreach (ServiceController dependentService in dependentServices) { WindowsService dependentServiceWrapper = new WindowsService(dependentService.ServiceName, dependentService.DisplayName, new WindowsServiceCollection()); //build the current service's dependencies WindowsServiceCollection.BuildDependentServiceHierarchy(dependentServiceWrapper, dependentService.DependentServices); //if the depdent services collection has yet to be created if (service.DependentServices == null) //create a new observable collection of dependent services service.DependentServices = new WindowsServiceCollection(); //add the depdency to the wrappers dependents collection service.DependentServices.Add(dependentServiceWrapper); } } } } ServiceMonitorViewModel.cs (This is the ViewModel and it basically loads all ServiceContoller classes and builds the corresponding WindowsServiceCollections and serves the data to the WPF MainWindow view via DataBinding.) using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.ServiceProcess; using System.Windows.Data; namespace WindowsServiceMonitor.ViewModels { public class ServiceMonitorViewModel { private ServiceController[] _serviceControllers; private WindowsServiceCollection _observableServices; public ServiceMonitorViewModel() { this.LoadSystemServices(); this.ObservableWindowsServices = new WindowsServiceCollection(); this.ObservableWindowsServices = _observableServices; //this.ObservableWindowsServices.Source = _observableServices; } public WindowsServiceCollection ObservableWindowsServices { get; set; } private void LoadSystemServices() { _serviceControllers = ServiceController.GetServices(); _observableServices = new WindowsServiceCollection(); _observableServices.LoadServices(_serviceControllers); } } } And finally we have MainWindow.xaml which is our WPF view. <Window x:Class="WindowsServiceMonitor.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:viewModel="clr-namespace:WindowsServiceMonitor.ViewModels" Title="MainWindow" SizeToContent="WidthAndHeight" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d"> <Window.Resources> <viewModel:ServiceMonitorViewModel x:Key="WindosServicesViewModel"/> <Style TargetType="ListBoxItem"> <Setter Property="FontFamily" Value="Verdana" /> <Setter Property="FontSize" Value="12"></Setter> <Setter Property="Padding" Value="10"></Setter> </Style> <DataTemplate x:Key="DetailTemplate"> <Border Margin="20" BorderBrush="Aqua" BorderThickness="1" Padding="8"> <Grid ScrollViewer.CanContentScroll="True" ScrollViewer.HorizontalScrollBarVisibility="Auto" ScrollViewer.VerticalScrollBarVisibility="Auto" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" > <Grid.RowDefinitions> <RowDefinition/> <RowDefinition/> <RowDefinition/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition/> <ColumnDefinition/> </Grid.ColumnDefinitions> <TextBlock Grid.Row="0" Grid.Column="0" Text="Service Name:"/> <TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Path=ServiceName}"/> <TextBlock Grid.Row="1" Grid.Column="0" Text="Display Name:"/> <TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding Path=DisplayName}"/> <TextBlock Grid.Row="2" Grid.Column="0" Text="Dependents:"/> <ListBox Name="lstDependentServices" Grid.Row="2" Grid.Column="1" IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding Path=DependentServices}" DisplayMemberPath="DisplayName" /> </Grid> </Border> </DataTemplate> </Window.Resources> <DockPanel> <StackPanel> <TextBlock>Windows Services</TextBlock> <ListBox Name="lstServices" HorizontalAlignment="Stretch" Height="300" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Center" VerticalAlignment="Stretch" DataContext="{Binding Source={StaticResource WindosServicesViewModel}}" ScrollViewer.VerticalScrollBarVisibility="Auto" IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding ObservableWindowsServices}"/> <TextBlock Grid.Row="0" Grid.Column="0" Text="Service Properties" /> <ContentControl DataContext="{Binding Source={StaticResource WindosServicesViewModel}}" Content="{Binding ObservableWindowsServices}" ContentTemplate="{StaticResource DetailTemplate}" /> </StackPanel> </DockPanel> </Window> And that about wraps it up.  Please note that each WindowsServiceCollection contains a WindowsServiceCollection of dependent windows services.  Also notice the many different uses of WPF databinding.  We bind the root level WindowsServiceCollection to a ListView and we bind  some TextBlocks to it's selection so that way when the user clicks to select a service, we can display a details view of the specified service. That's pretty much all there is to it.  I can say that I learned a lot by writing this application and I had a lot of fun as well. Here is a link to the entire solution for you to download WindowsServiceMonitor.zip (2.92 mb)  I hope you have enjoyed this post and I hope you will check back soon! Thanks! ~/Buddy James     kick it on DotNetKicks.com  


WPF Validation tutorial for the rest of us. Learn to use IDataErrorInfo to automatically validate your views.

    WPF Validation for mere mortals I've recently jumped on the WPF bandwagon and I've fallen in love with this technology.  XAML is a fascinating animal indeed.  The declarative nature of the language leaves much to be explored.  There are many ways to solve the same problem.  On my quest for knowledge, I've been researching the intrinsic validation functionality of WPF.  Unfortunately, most every example I've ran across on blog posts and codeproject.com have been a bit too complex for my blood.  I find often that you need learn other subjects before you can begin to understand how the validation works.  Don't get me wrong, the examples are really nice.  However, when I'm learning something, I want a straight to the point example of the topic at hand.  It's with this idea in mind that I bring you a simple tutorial on WPF validation. I will be illustrating this example using the MVVM (Model-View-ViewModel) Pattern.   Click here to download the entire source WPFMVVMValidation.zip (74.08 kb)  Consider the following code  The view MainWindow.xaml <Window x:Class="ExceptionValidation.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:viewModel="clr-namespace:ExceptionValidation" Title="MainWindow" Height="350" Width="525" > <Window.Resources> <viewModel:MainWindowViewModel x:Key="mainViewModel"/> </Window.Resources> <StackPanel DataContext="{Binding Source={StaticResource mainViewModel }}"> <TextBlock>Enter total amount</TextBlock> <TextBox Width="200" Name="txtTotalAmount" > <Binding Path="[0].TotalAmount" ValidatesOnDataErrors="True"> <Binding.ValidationRules> <ExceptionValidationRule></ExceptionValidationRule> </Binding.ValidationRules> </Binding> </TextBox> <Button Content="Button" Height="28" Name="button1" Width="84" /> </StackPanel> </Window>     The viewmodel MainWindowViewModel.cs using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.ComponentModel; namespace ExceptionValidation { class MainWindowViewModel : ObservableCollection<Product> { public MainWindowViewModel() { Add(new Product { TotalAmount = 3 }); } } }   The model Product.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; namespace ExceptionValidation { public class Product : INotifyPropertyChanged , IDataErrorInfo { public event PropertyChangedEventHandler PropertyChanged; private int _totalAmount = 5; public int TotalAmount { get { return _totalAmount; } set { _totalAmount = value; OnPropertyChanged("TotalAmount"); } } public void OnPropertyChanged(string info) { PropertyChangedEventHandler handler = PropertyChanged; if (PropertyChanged != null) { handler(this, new PropertyChangedEventArgs(info)); } } public string Error { get { throw new NotImplementedException(); } } public string this[string columnName] { get { if (columnName == "TotalAmount") { bool valid = true; if (_totalAmount > 10) { valid = false; } if (!valid) { return "The total amount cannot exceed 10!"; } } return null; } } } } A brief introduction to MVVM  As you can see, we have a XAML view, a viewmodel class, and a model.  The Model is a representation of an object's data.  In this instance, we are modeling a Product.  The viewmodel is an object that handles the change notification between properties in the model and elements on the view.  XAML properties, events, and bindings have the ability to tunnel (down the tree) as well as bubble (up the tree).   Binding the ViewModel to the view. In order to bind the ViewModel to the view, we must make it accessible to the view via XAML.  To accomplish this, we first have to import the namespace in which the viewmodel exists.  Examine the following code. xmlns:viewModel="clr-namespace:ExceptionValidation" Here is the equivalent in c# using ExceptionValidation; Once we've imported the namespace for use, we then need to define our MainWindowViewModel as a Resource of the current window. <Window.Resources> <viewModel:MainWindowViewModel x:Key="mainViewModel"/> </Window.Resources> This allows us to declare an instance of the MainWindowViewModel class by using the associated Key "mainViewModel". Binding the ViewModel As stated before the ViewModel acts as a "go between" for the View and the Model.  In order for the view model to communicate with our XAML view, we will bind the ViewModel to the StackPanel's DataContext. <StackPanel DataContext="{Binding Source={StaticResource mainViewModel }}"> XAML's ability to tunnel properties down from parent to child will allow each element inside the stack panel to make use of the DataContext binding that we've just setup using the Window resource's key mainViewModel. ObservableCollection<T> The viewmodel inherits from ObservableCollection<Product>.  The ObservableCollection<T> generic class represents a collection that can be utilized by WPF databinding.  This is possible because the ObservableCollection<T> class raises an event when items are added and removed from the collection. INotifyPropertyChanged The model implements the INotifyPropertyChanged interface.  This interface provides an event in which to fire any time a model property is changed.  This event notifies the bound element in the view that the property has changed. public event PropertyChangedEventHandler PropertyChanged;   public void OnPropertyChanged(string info) { PropertyChangedEventHandler handler = PropertyChanged; if (PropertyChanged != null) { handler(this, new PropertyChangedEventArgs(info)); } }   IDataErrorInfo The magic behind WPF validation comes from the implementation of the IDataErrrorInfo interface.  The interface implements the following members.  The this[columnName] indexer implements the logic of the validation rule. //Not used by WPF public string Error { get { throw new NotImplementedException(); } } public string this[string columnName] { get { if (columnName == "TotalAmount") { bool valid = true; if (_totalAmount > 10) { valid = false; } if (!valid) { return "The total amount cannot exceed 10!"; } } return null; } } The following XAML code binds the TotalAmount property of the first Product in the viewmodel's internal collection to the Text property of the TextBox element.  The ValidatesOnDataErrors attribute tells the textbox binding to raise an event when there is a valadation error.  When the event is raised, the bound element's template is changed to a new visual style that places a Red rectangle around the border of the TextBox.  When the error is corrected, the original template is restored.  Binding.ValidatesOnDataErrors <TextBox Width="200" Name="txtTotalAmount" > <Binding Path="[0].TotalAmount" ValidatesOnDataErrors="True"> </Binding> </TextBox> In the provided example, if you enter a value greater than 10 into the text box and tab out of the textbox, you will see that an error is raised causing the red outline around the textbox.  If you correct the error by replacing the value with a number less than 10, the red outline will disappear. This concludes my tutorial on WPF validation.  This is the very basic of validation methods.  There are many other advanced tutorials on the subject.  My next tutorial will involve utilizing custom validation attributes from the System.ComponentModel namespace to handle WPF view validation. Thanks for reading! ~/Buddy James kick it on DotNetKicks.com  


About the author

My name is Buddy James.  I'm a Microsoft Certified Solutions Developer from the Nashville, TN area.  I'm a Software Engineer, an author, a blogger (http://www.refactorthis.net), a mentor, a thought leader, a technologist, a data scientist, and a husband.  I enjoy working with design patterns, data mining, c#, WPF, Silverlight, WinRT, XAML, ASP.NET, python, CouchDB, RavenDB, Hadoop, Android(MonoDroid), iOS (MonoTouch), and Machine Learning. I love technology and I love to develop software, collect data, analyze the data, and learn from the data.  When I'm not coding,  I'm determined to make a difference in the world by using data and machine learning techniques. (follow me at @budbjames).  

Related links

Month List