Infragistics JQuery controls

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      


WPF Snoop: A must have tool for WPF development.

WPF Snoop: A WPF developers dream WPF is the latest development methodology for developing Windows Desktop applications.  If you come from a WinForms background, there is a considerably steep learning curve that comes along with WPF.  This is in part due to the nature of the XAML declarative markup.  You can instantiate objects,  execute data binding and many other complex tasks all without touching a line of c#.  Couple this with the new flow style layout of WPF user interfaces, there's plenty for a new developer to learn.  While surfing online I ran across an open source tool on codeplex that greatly reduces some of the complexities of developing in WPF. WPF Snoop and what it can do for you Imagine you've downloaded an example WPF application with the best user interface you've ever seen.  You are new to WPF, so despite your best efforts, you can't quite grasp how the UI is tied together.  What if you had an application that allowed you to attach to the application and  allowed you to view the visual tree of the application's user interface?  Imagine viewing each and every control, and property in the entire UI. Better yet, imagine the ability to change the properties of the UI controls on the fly?   WPF snoop also makes debugging WPF data binding a breeze!  You can select a data bound ListView and view as well as modify the ItemsSource.  WPF Snoop can achieve all of this and more! Here's a quick tutorial.. Download WPF snoop To begin, download WPF snoop from the following URL http://snoopwpf.codeplex.com/ Once installed, launch the application.  The application toolbar looks like this.     Next, launch the application that you wish to snoop.  I'm going to use a school course editor example that I found on the codeproject. I then click the crosshair and drag it over the application that I wish to snoop. I'm then presented with a dialog that contains the visual tree and all of the properties of the controls.   As I drill down into the visual tree, I can hover over each node and it will display a thumbnail of the contents of that node.  Once I've reached a part of the UI that I wish to isolate, I can click on the node and this will actually draw a red border around the area in the application.  Here is a screen shot for your reference.     Also notice the tabbed interface.  When you click on the DataContext tab, you can view all of the relevant data binding information.  Keep in mind that all of the properties can be changed on the fly. The possibilities are endless.   This concludes my tutorial on WPF snoop.  I suggest you download it and start snooping around. This tool will help beginners and newbies alike.   Until next time!  Cheers! ~/Buddy James kick it on DotNetKicks.com


Introducing System.Threading.Tasks namespace. Exploring Action<>, Task<>, and the BusyIndicator.

Introduction The Microsoft .NET framework class library has provided many classes to facilitate complex programming tasks.  Topics like I/O, database management, and sockets were once incredibly tough to implement in languages like C, C++ and VB6.  When .NET was released, it brought with it many classes that abstracted these complex concepts and allowed the developer to concentrate on the business task at hand.  Multithreading is a way of providing asynchronous code execution and is an advanced concept that the framework has greatly simplified.  The System.Threading namespace The System.Threading namespace contains classes to abstract the complexities of multithreaded programming away from the developer.  Multithreading allows you to spawn worker threads to accomplish a unit of code execution.  System.Threading includes classes for synchronizing thread activities as well as accessing shared data .  These classes include; Mutex, Monitor, Interlocked, AutoResetEvent and more.   At the heart of the System.Threading namespace is the System.Threading.Thread class.  This class represents an asynchronous thread of code execution.  The Thread class accepts a delegate to specify a method that returns void and is to be executed independently in regards to the thread that spawned it.  This was one of the first methods of asynchronous programming that was offered to .NET developers. Here's an example using System; using System.Threading; namespace AnsycThread { class Program { delegate void LongRunningComputation(); private static void LongRunningMethod() { //Add a long running computation here for(var loopCounter=0; loopCounter < 100; loopCounter++) { Console.WriteLine(string.Format("The value = {0} ", loopCounter)); } Console.ReadKey(); } public static void Main(string[] args) { LongRunningComputation codeBlock = LongRunningMethod; Thread spawnedWorker = new Thread(new ThreadStart(codeBlock)); spawnedWorker.Start(); Console.WriteLine("The thread has started."); Console.ReadKey(); } } } This code is not very complicated, especially when compared to the same take written in a language like C or C++.  The System.Threading namespace has been around since the first release of the .NET framework. Enter the System.Threading.Tasks.Task class With .NET 4 came the System.Threading.Tasks namespace.  The idea of a Thread is a low level concept.  To think in terms of processes, threads, and thread management is to think at the level a computers processor.  The Task class was created to abstract these machine level ideas away from the developer so that we could achieve the same solutions that multithreading offers but from the viewpoint of task and workflows instead of threads and processors.  Much like the System.Threading.Thread class, the Task class is simply an asynchronous operation represented by a delegate.  However, there are some key differences.  For instance, there is a generic Taks<T> where T represents the return type of the delegate.  The Task class also handles a lot of the manual aspects of multithreaded programming such as picking a thread from the thread pool, as well as optimization with multicore/multiprocessor systems.  The System.Threading.Tasks namespace event offers functionality to support parallelism, but I'm getting ahead of myself. We are going to examine an example that makes use of the Task class as well as the System.Action class. The System.Action class represents a delegate that takes no arguments and returns void.  There is a generic version of the Action class as well.  It greatly simplifies the syntax of delegates. Consider the following example which is essentially the same as the prior example, except this example uses the Task and Action classes instead of Thread and delegate. namespace AnsycTask { class Program { private static void LongRunningMethod() { //Add a long running computation here for(var loopCounter=0; loopCounter < 100; loopCounter++) { Console.WriteLine(string.Format("The value = {0} ", loopCounter)); } Console.WriteLine("Press a key"); Console.ReadKey(); } public static void Main(string[] args) { Action codeBlock = LongRunningMethod; var spawnedWorker = new Task(codeBlock); spawnedWorker.Start(); Console.WriteLine("The thread has started."); Console.ReadKey(); } } } Accessing the UI from another thread using Dispatcher.BeginInvoke As you can see, multithreaded programming and allow you to complete multiple computing tasks simultaneously.  One of the draw backs of this approach is the fact that you can't directly access controls that were instantiated on the UI thread from your Tasks or Threads.  This is where the System.Windows.Dispatcher class can help.  When you call the BeginInvoke method of the Dispatcher class, it allows you to execute an asynchronous delegate on the same thread that the Dispatcher is associated.  I've included an example that uses the Task, Action, and Dispatcher classes in a WPF application.   This example will execute a Task when the user clicks a button.  The task will open a text file and read the contents of the file.  We use the ContinueWith method of the Task object to specify another Task to run when the first task has completed.  In the ContinueWith Task, we will use the Dispatcher class to set the IsBusy property on a BusyIndicator object.  The BusyIndicator class comes from the WPF Extended toolkit.   Here's the example.. <Window x:Class="FileReadBusyIndicator.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:extToolkit="clr-namespace:Xceed.Wpf.Toolkit;assembly=WPFToolkit.Extended" Title="MainWindow" Height="350" Width="525"> <extToolkit:BusyIndicator x:Name="busyIndicator"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="78*" /> <RowDefinition Height="78*" /> <RowDefinition Height="106*" /> <RowDefinition Height="50*" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition /> </Grid.ColumnDefinitions> <Button Content="Load File" Grid.Column="1" Grid.Row="3" Height="23" HorizontalAlignment="Left" Margin="118,9,0,0" Name="btnLoadFile" VerticalAlignment="Top" Width="75" Click="btnLoadFile_Click" /> <TextBlock Height="45" HorizontalAlignment="Left" Margin="32,15,0,0" Name="txtDescription" Text="Click the button below to asynchrnously load the contents of the text file specified in the textbox." VerticalAlignment="Top" Grid.ColumnSpan="2" Width="390" /> <TextBlock x:Name="txtContents" Grid.Row="1" ScrollViewer.CanContentScroll="True" Height="183" HorizontalAlignment="Left" Margin="6,0,0,0" Text="rwaraadsadsdsasdafsdfsdafsdaf" VerticalAlignment="Top" Width="491" Grid.ColumnSpan="2" Grid.RowSpan="2"> </TextBlock> </Grid> </extToolkit:BusyIndicator> </Window> And for the codebehind 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 System.Threading.Tasks; using Microsoft.Practices.Unity; using System.IO; using System.ComponentModel; using System.Threading; using System.Windows.Threading; using Xceed.Wpf.Toolkit; namespace FileReadBusyIndicator { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { private void LongRunningMethod() { //Add a long running computation here for (var loopCounter = 0; loopCounter < 100; loopCounter++) { using (var streamReader = new StreamReader(@"c:\development\openme.txt")) { var contents = streamReader.ReadToEnd(); Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { this.txtContents.SetValue(TextBlock.TextProperty, contents); }, null); } } } public MainWindow() { InitializeComponent(); } private void btnLoadFile_Click(object sender, RoutedEventArgs e) { busyIndicator.IsBusy = true; Action readFile = LongRunningMethod; var spawnedWorker = new Task(readFile); var completedTask = new Action<Task>((t) => { Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { busyIndicator.SetValue(BusyIndicator.IsBusyProperty, false); }, null); }); spawnedWorker.ContinueWith(completedTask); spawnedWorker.Start(); } } } As you can see, the button's click event handler sets the BusyIndicator's IsBusy property to true which will show the ProgressBar.  Next the event handler will create a Task and set it to execute an action that points to a method to read the contents of a file.  The method will use the Dispatcher class to set the TextProperty dependency property of a textbox to the contents of the text file.  When the task completes its execution, it will proceed to execute the task specified in the ContinueWith method which uses the Dispatcher class to set the BusyIndicator's IsBusyProperty dependency property's value to false, causing the ProgressBar to be hidden. You can download the source to the example projects here AsyncTaskExample.zip (352.19 kb). This concludes my introduction to the System.Threading.Tasks namespace. Thanks for reading. ~/Buddy James   kick it on DotNetKicks.com    


How to keep your WPF UI responsive and report progress during a long running task. C# and asynchronous multithreading.

    The problem Have you ever had to execute a bit of code that took an extremely long time to complete?  If so, I'm sure you've noticed that your user interface becomes unresponsive.  You can't use any controls on the form until the process completes.  This is extremely problematic and makes for a poor user experience. The cause This problem is because you have executed a synchronous block of code on the same thread as the user interface.  The user interface will not be able to respond to any user action until the synchronous method has completed. Let's look at an example that illustrates the execution of a synchronous method executing on the user interface thread. The example   This example is very simple.  It's a WPF application with two buttons.   One of the buttons will start a long running for loop and the other button opens a MessageBox and displays a message to let you know that the UI is active. When you click the button to start the long running process, try to click the other button.   You will notice that you are unable to click the button to show the message box.   Here's the MainWindow.xaml markup <Window x:Class="SynchronousExecution.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid Width="111" Height="118"> <Button Content="Start Process" Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" Name="btnStartProcess" VerticalAlignment="Top" Width="89" Click="btnStartProcess_Click" /> <Button Content="Try to click me" Height="23" HorizontalAlignment="Left" Margin="10,43,0,0" Name="btnTryMe" VerticalAlignment="Top" Width="89" Click="btnTryMe_Click" /> </Grid> </Window>   And here is the code behind MainWindow.xaml.cs 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 System.Threading; namespace SynchronousExecution { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void btnStartProcess_Click(object sender, RoutedEventArgs e) { MessageBox.Show("Starting the long process. Try to click the button below."); for (var loopCounter = 0; loopCounter < 500; loopCounter++) { Thread.Sleep(100); } MessageBox.Show("The process has ended."); } private void btnTryMe_Click(object sender, RoutedEventArgs e) { MessageBox.Show("User interface is responding!"); } } } Download  SynchronousExecution.zip (52.38 kb) The solution The solution to this problem is to spawn a new thread to execute the long running task.  By placing the execution on a seperate thread, this leaves the main UI thread free to interact with the user's input. Reporting progress  If you execute a long running task, you usually want to let your users know about the progress of the task.  A control to assist with this is the progressbar control.   The WPF progress bar control inherits from the RangeBase class.  The control contains the following properties to control how the progress is displayed to the user. Minimum The minimum value of the Value property. Maximum The maximum value of the Value property. SmallChange The value in which the Value property is incremented. Value The current value position between the Minimum and Maximum property. Multithreading concerns Multithreading is a complex topic and is beyond the scope of this article.  However, there are a few concerns that you must be aware of if you plan to access values on the UI thread from the worker thread. The System.Windows.Threading.Dispatcher object is used to execute code on the UI thread from the executing worker thread.  The Dispatcher object has the BeginInvoke method which will execute an asynchronous delegate on the thread in which the dispatcher object was created.  So by using the dispatcher object from the user interface code you are able to access the user interface controls from your worker thread. We'll take a look at another example that will bring all of these concepts together to illustrate executing a long running task on a seperate thread with a progress bar that updates the user interface via the Dispatcher object. The example The example is a WPF application.  The main window contains the following controls; lstRandomValues A ListBox control that will hold random values that are generated during the long running process. The pupose of this control is to illustrate the responsiveness of the user interface during the long running process. prgProgress A ProgressBar control that will illustrate the progress of the long running task. The ProgressBar is hidden by default. It's shown when the long running process begins and is hidden again when the process has ended or is canceled. txtProgress A TextBox control that displays the long running process percentage of completion. btnCancel A Button control that will cancel the long running process and in turn hide the progress bar and progress textbox. btnInteract A Button control that will launch a MessageBox to illustrate the responsiveness of the UI while the long running process is executing. btnBegin A Button control that will begin the long running process. And here is the code  Window1.xaml <Window x:Class="RandomNameSpace.ViewModels.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="400" Width="400"> <!-- Parent Grid --> <Grid> <Grid.RowDefinitions> <RowDefinition /> <RowDefinition /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition /> </Grid.ColumnDefinitions> <ListBox Grid.Row="0" Grid.Column="0" Name="lstRandomValues" Grid.ColumnSpan="2" /> <Grid Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2"> <Grid.RowDefinitions> <RowDefinition /> <RowDefinition /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition /> </Grid.ColumnDefinitions> <Border Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2" x:Name="bdrProgress" Visibility="Hidden" Background="Azure" CornerRadius="10" BorderBrush="DarkGray" BorderThickness="1" HorizontalAlignment="Center" VerticalAlignment="Center"> <StackPanel> <Grid Margin="5"> <ProgressBar x:Name="prgProgress" Width="200" Height="20" Minimum="0" Maximum="1" /> <TextBlock x:Name="txtProgress" HorizontalAlignment="Center" VerticalAlignment="Center" /> </Grid> <Button x:Name="btnCancel" Content="Cancel" HorizontalAlignment="Right" Margin="3" Click="btnCancel_Click" /> </StackPanel> </Border> <Button Grid.Row="1" Grid.Column="1" x:Name="btnInteract" HorizontalAlignment="Center" Content="Interact with UI" Click="btnInteract_Click" Height="23.96" /> <Button Grid.Row="1" Grid.Column="0" x:Name="btnBegin" HorizontalAlignment="Left" Content="Start Long Process" Click="btnBegin_Click" Height="23.96" Margin="35,33.27,0,33.27" /> </Grid> </Grid> </Window> Window1.xaml.cs 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 System.Threading; using System.Windows.Threading; namespace RandomNameSpace.ViewModels { /// <summary> /// Interaction logic for Window1.xaml /// </summary> public partial class Window1 : Window { private bool IsCanceled = false; private RandomViewModel _viewModel; public RandomViewModel ViewModel { get { return _viewModel; } set { _viewModel = value; } } public Window1() { InitializeComponent(); PrepareViewModel(); } private void PrepareViewModel() { ViewModel = new RandomViewModel(); this.lstRandomValues.DisplayMemberPath = "Value"; this.lstRandomValues.DataContext = ViewModel; this.lstRandomValues.ItemsSource = ViewModel; } private void btnBegin_Click(object sender, RoutedEventArgs e) { BeginProcess(); } private void btnInteract_Click(object sender, RoutedEventArgs e) { MessageBox.Show("Interaction!"); } private void btnCancel_Click(object sender, RoutedEventArgs e) { CancelProcess(); } public void BeginProcess() { bdrProgress.Visibility = System.Windows.Visibility.Visible; DisableBeginButton(); Action StartLoop; StartLoop = () => DoLongRunningProcess(); Thread t; t = new Thread(StartLoop.Invoke); t.Start(); } public void CancelProcess() { this.IsCanceled = true; Thread.Sleep(1500); ClearListBox(); EnableBeginButton(); } private void ClearListBox() { Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { this.ViewModel.Clear(); }, null); } private void DoLongRunningProcess() { for (var loopCounter = 0.0; loopCounter < 1.0; loopCounter = loopCounter + .1) { if (!IsCanceled) { //add a random number to the viewmodel collection to be bound to the listview Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { this.ViewModel.AddValue(1564); }, null); UpdateProgressBar(loopCounter); Thread.Sleep(2000); } else { break; } } IsCanceled = false; ClearListBox(); MessageBox.Show("Completed"); EnableBeginButton(); HideProgressBar(); } private void EnableBeginButton() { Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { this.btnBegin.SetValue(Button.IsEnabledProperty, true); }, null); } private void DisableBeginButton() { Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { this.btnBegin.SetValue(Button.IsEnabledProperty, false); }, null); } private void UpdateProgressBar(double value) { Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { this.prgProgress.SetValue(ProgressBar.ValueProperty, value); }, null); Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { this.txtProgress.SetValue(TextBlock.TextProperty, (value * 100).ToString()); }, null); } private void HideProgressBar() { Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { this.bdrProgress.SetValue(Border.VisibilityProperty, Visibility.Collapsed); }, null); } } }   RandomValue.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; namespace RandomNameSpace.ViewModels { public class RandomValue : INotifyPropertyChanged { private int _value; public int Value { get { return _value; } set { if (_value != value) _value = value; OnPropertyChanged("Value"); } } public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged(string propertyName) { var handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } } } RandomViewModel.cs using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading; using System.Windows; using System.Windows.Controls; using System.Windows.Threading; namespace RandomNameSpace.ViewModels { public class RandomViewModel : ObservableCollection<RandomValue> { public RandomViewModel() : base() {} public void AddValue(int value) { Random rnd = new Random(); var calculatedValue = (value * rnd.Next(3000)); this.Add(new RandomValue { Value = (calculatedValue) }); } } } Here is the entire solution for download.  WPFAsyncProgressBarMVVM.zip (77.39 kb)   This concludes the article.  Thank you for taking the time to read it! Until next time... ~/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