<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rssdatehelper="urn:rssdatehelper" version="2.0"><channel><title>Pete Brown's Blog (POKE 53280,0) for tag Tutorial-General-WPF</title><link>http://10rem.net</link><pubDate /><description>Pete Brown writes on a variety of topics from XAML with the Windows Runtime (WinRT), .NET programming using C#, WPF, Silverlight, XNA, and Windows Phone, Microcontroller programming with .NET Microframework, .NET Gadgeteer and even plain old C, to raising two children in the suburbs of Maryland, woodworking, CNC and generally "making physical stuff". Oh, and Pete loves retro technology, especially Commodore (C64 and C128). If the content interests you, please subscribe using the subscription link to the right of every page.</description><generator>umbraco</generator><language>en-us</language><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/PeteBrown-GeneralWPFTutorials" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="petebrown-generalwpftutorials" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item><title>Threading Considerations for Binding and Change Notification in Silverlight 5</title><author>Pete Brown	</author><link>http://10rem.net/blog/2012/01/10/threading-considerations-for-binding-and-change-notification-in-silverlight-5</link><pubDate>Tue, 10 Jan 2012 16:48:00 GMT</pubDate><guid>http://10rem.net/blog/2012/01/10/threading-considerations-for-binding-and-change-notification-in-silverlight-5</guid><description><![CDATA[ 
<p>A reader of <a href="http://manning.com/pbrown2"
target="_blank">my Silverlight 5 book</a> recently reached out to
me about threading and why I create some objects on the UI thread
in the examples. We discussed some of the reasons, but I felt this
would be a good topic to share with everyone. In fact, this is one
area where it would have been fun to go into great detail in my
book, but there simply wasn't the space. Threading and cross-thread
exceptions can be a bit of a mystery to new Silverlight and WPF
developers.</p>

<h3>Background</h3>

<p>The user interface in Silverlight runs on a thread commonly
known as the UI Thread. Any code you create in the code-behind, and
any code it calls all the way down the chain, unless it explicitly
creates another thread, runs on this same UI thread. It's not at
all uncommon to see Silverlight and WPF applications which never
explicitly create a second thread, but do make calls to other
services which create background threads for processing.</p>

<p>There are many other examples, but networking is one place where
the Silverlight .NET Framework explicitly creates (or uses)
different threads. Not all calls return on the UI thread.</p>

<p><strong>Threads other than the UI thread are not allowed to
access or manipulate UI objects</strong>. If they attempt to do so,
the runtime throws an Invalid Cross-Thread Access exception. It
looks like this:</p>

<p><a
href="http://10rem.net/media/82267/Windows-Live-Writer_Threading-Considerations-for-Binding-in-_EF97_image_2.png"
 target="_blank"><img src="http://10rem.net/media/82272/Windows-Live-Writer_Threading-Considerations-for-Binding-in-_EF97_image_thumb.png" width="477" height="277" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></a></p>

<p>But wait! I wasn't accessing any UI objects from my code. What
gives?</p>

<p>It's not always obvious that you're interacting with UI objects
on the UI thread, though. Here's the stack trace from this
particular exception:</p>

<pre class="brush: csharp; highlight: [2];">
{System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---&gt;<br />
  System.UnauthorizedAccessException: Invalid cross-thread access.<br />
   at MS.Internal.XcpImports.CheckThread()<br />
   at MS.Internal.XcpImports.GetValue(IManagedPeerBase managedPeer, DependencyProperty property)<br />
   at System.Windows.DependencyObject.GetOldValue(DependencyProperty property, EffectiveValueEntry&amp; oldEntry)<br />
   at System.Windows.DependencyObject.UpdateEffectiveValue(DependencyProperty property, EffectiveValueEntry oldEntry, EffectiveValueEntry&amp; newEntry, ValueOperation operation)<br />
   at System.Windows.DependencyObject.RefreshExpression(DependencyProperty dp)<br />
   at System.Windows.Data.BindingExpression.SendDataToTarget()<br />
   at System.Windows.Data.BindingExpression.SourcePropertyChanged(PropertyPathListener sender, PropertyPathChangedEventArgs args)<br />
   at System.Windows.PropertyPathListener.ReconnectPath()<br />
   at System.Windows.Data.Debugging.BindingBreakPoint.&lt;&gt;c__DisplayClass4.&lt;BreakOnSharedType&gt;b__3()<br />
   --- End of inner exception stack trace ---<br />
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)<br />
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)<br />
   at System.Delegate.DynamicInvokeImpl(Object[] args)<br />
   at System.Delegate.DynamicInvoke(Object[] args)<br />
   at MainPagexaml.BindingOperation(Object BindingState, Int32 , Action )}
</pre>

<p>This stack trace was generated by <strong>trying to raise a
PropertyChangedNotification when I manipulated a model object from
a background thread</strong>. So, it was obvious that I was working
with an object on the background thread, but it wasn't obvious that
I'd get a cross-thread exception (well it was in this case, as I
contrived the example). If you consider a larger application where
you have division of ownership for different pieces, a client-side
developer may simply work with your viewmodel, but not realize
you're farming some work out to another thread.</p>

<p>I wrote a blog post back in 2010 ( <a
href="http://10rem.net/blog/2010/04/23/essential-silverlight-and-wpf-skills-the-ui-thread-dispatchers-background-workers-and-async-network-programming">
Essential Silverlight and WPF Skills: The UI Thread, Dispatchers,
Background Workers and Async Network Programming</a>) explaining
some of the ways to work with threads and dispatching. I didn't
have SynchronizationContext in there at the time, but it's
something I tend to use a lot these days.</p>

<p>Let's take a look at a few of the common scenarios and how it
works with threading.</p>

<h3>Common Scenarios</h3>

<p>All of these scenarios make use of a simple Customer class with
a single property:</p>

<pre class="brush: csharp;">
namespace SilverlightThreadingExample.Model<br />
{<br />
    public class Customer : Observable<br />
    {<br />
        private string _firstName;<br />
        public string FirstName<br />
        {<br />
            get { return _firstName; }<br />
            set { _firstName = value; NotifyPropertyChanged("FirstName"); }<br />
        }<br />
    }<br />
}
</pre>

<p>The customer is <em>observable</em> that is, it notifies any
listeners when properties change. While not necessary, I
encapsulated the observable code in this base class. You could,
instead, put the implementation in a partial class if you wanted to
make sure your model object's signature from your ORM or whatever
remains the same as it was on the server.</p>

<pre class="brush: csharp;">
using System.ComponentModel;<br />
<br />
namespace SilverlightThreadingExample<br />
{<br />
    public class Observable : INotifyPropertyChanged<br />
    {<br />
        public event PropertyChangedEventHandler PropertyChanged;<br />
<br />
        protected void NotifyPropertyChanged(string propertyName)<br />
        {<br />
            if (PropertyChanged != null)<br />
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));<br />
        }<br />
    }<br />
}
</pre>

<p>This is actually a pretty typical approach to handling
INotifyPropertyChanged. There are even more robust versions out
there which use lambdas and reflection to help avoid passing in
strings, but they ultimately come down to raising the
PropertyChanged event. Many of them also fail to work properly in
cross-thread situations.</p>

<p>I expose the Customer class and a collection of customers from a
ViewModel class.</p>

<pre class="brush: csharp;">
namespace SilverlightThreadingExample.ViewModel<br />
{<br />
    public class CustomerEntryViewModel : Observable<br />
    {<br />
        private Customer _currentCustomer;<br />
        public Customer CurrentCustomer<br />
        {<br />
            get { return _currentCustomer; }<br />
            set { _currentCustomer = value; NotifyPropertyChanged("CurrentCustomer"); }<br />
        }<br />
<br />
        private ObservableCollection&lt;Customer&gt; _customers = new ObservableCollection&lt;Customer&gt;();<br />
        public ObservableCollection&lt;Customer&gt; Customers<br />
        {<br />
            get { return _customers; }<br />
        }<br />
<br />
        public void LoadCustomersOnSameThread()<br />
        {<br />
            LoadDummyData();<br />
        }<br />
<br />
        private void LoadDummyData()<br />
        {<br />
            _customers.Add(new Customer() { FirstName = "Pete" });<br />
            _customers.Add(new Customer() { FirstName = "Jon" });<br />
            _customers.Add(new Customer() { FirstName = "Tim" });<br />
            _customers.Add(new Customer() { FirstName = "Scott" });<br />
            _customers.Add(new Customer() { FirstName = "Andy" });<br />
            _customers.Add(new Customer() { FirstName = "Blaine" });<br />
            _customers.Add(new Customer() { FirstName = "Jesse" });<br />
            _customers.Add(new Customer() { FirstName = "Rey" });<br />
<br />
            _currentCustomer = _customers[0];<br />
        }<br />
<br />
    }<br />
}
</pre>

<p>Finally, the UI is bound to those classes. The DataContext for
the UI (which will be set in code-behind) is the ViewModel.</p>

<pre class="brush: xml;">
&lt;UserControl x:Class="SilverlightThreadingExample.MainPage"<br />
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"<br />
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"<br />
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"<br />
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"<br />
    mc:Ignorable="d"<br />
    d:DesignHeight="400" d:DesignWidth="600"&gt;<br />
<br />
    &lt;Grid x:Name="LayoutRoot" Background="White"&gt;<br />
        &lt;Grid Width="500"&gt;<br />
            &lt;Grid.ColumnDefinitions&gt;<br />
                &lt;ColumnDefinition Width="*" /&gt;<br />
                &lt;ColumnDefinition Width="250" /&gt;<br />
            &lt;/Grid.ColumnDefinitions&gt;<br />
<br />
            &lt;ListBox x:Name="CustomerList"<br />
                     Grid.Column="0" Margin="10"<br />
                     ItemsSource="{Binding Customers}"<br />
                     SelectedItem="{Binding CurrentCustomer, Mode=TwoWay}"&gt;<br />
                &lt;ListBox.ItemTemplate&gt;<br />
                    &lt;DataTemplate&gt;<br />
                        &lt;TextBlock Text="{Binding FirstName}" /&gt;<br />
                    &lt;/DataTemplate&gt;<br />
                &lt;/ListBox.ItemTemplate&gt;<br />
            &lt;/ListBox&gt;<br />
<br />
            &lt;StackPanel Grid.Column="1"&gt;<br />
                &lt;TextBox x:Name="FirstNameField" Margin="10"<br />
                         DataContext="{Binding CurrentCustomer}"<br />
                         Text="{Binding FirstName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" /&gt;<br />
<br />
                &lt;Button x:Name="AddCustomer"<br />
                        Content="Add Customer from UI Thread"<br />
                        Height="30" Margin="5"<br />
                        Click="AddCustomer_Click" /&gt;<br />
                &lt;Button x:Name="AddCustomerSecond"<br />
                        Content="Add Customer from Second Thread"<br />
                        Height="30" Margin="5"<br />
                        Click="AddCustomerSecond_Click" /&gt;<br />
                &lt;Button x:Name="ChangeNameFromSecondThread"<br />
                        Content="Change Name from Second Thread"<br />
                        Height="30" Margin="5"<br />
                        Click="ChangeNameFromSecondThread_Click" /&gt;<br />
            &lt;/StackPanel&gt;<br />
<br />
        &lt;/Grid&gt;<br />
   <br />
    &lt;/Grid&gt;<br />
&lt;/UserControl&gt;
</pre>

<p>The code-behind looks like this</p>

<pre class="brush: csharp;">
using System.Windows;<br />
using System.Windows.Controls;<br />
using SilverlightThreadingExample.ViewModel;<br />
using System.Threading;<br />
using SilverlightThreadingExample.Model;<br />
<br />
namespace SilverlightThreadingExample<br />
{<br />
    public partial class MainPage : UserControl<br />
    {<br />
        CustomerEntryViewModel _vm;<br />
<br />
        public MainPage()<br />
        {<br />
            InitializeComponent();<br />
<br />
            CreateViewModelOnUIThread();<br />
        }<br />
<br />
<br />
        private void CreateViewModelOnUIThread()<br />
        {<br />
            _vm = new CustomerEntryViewModel();<br />
<br />
            _vm.LoadCustomersOnSameThread();<br />
<br />
            DataContext = _vm;<br />
        }<br />
<br />
<br />
        private void AddCustomer_Click(object sender, RoutedEventArgs e)<br />
        {<br />
        }<br />
<br />
<br />
        private void AddCustomerSecond_Click(object sender, RoutedEventArgs e)<br />
        {<br />
        }<br />
<br />
<br />
        private void ChangeNameFromSecondThread_Click(object sender, RoutedEventArgs e)<br />
        {<br />
        }<br />
<br />
<br />
    }<br />
}<br />
</pre>

<p>The methods are named to keep the context clear in this example.
I wouldn't expect you to name your VM instantiation/locator method
"CreateViewModelOnUIThread", for example.</p>

<p>Now let's look at those scenarios.</p>

<h4>Changing a property value from a background thread</h4>

<p>Often in an application, you have a class which is used in UI
binding (an entity/model object) but still need to modify a
property from code. Sometimes, you need to do that from a
background thread. For example, you make a network call to get an
updated price for an item. You will get a cross-thread access error
when the class raises change notification events from that property
setter. If the class is truly POCO (Plan Old CLR Object) and
doesn't do any change notification or other event raising, you'll
be fine. If, however, change notification is involved, you'll get
the cross-thread exception.</p>

<p><img src="http://10rem.net/media/82277/Windows-Live-Writer_Threading-Considerations-for-Binding-in-_EF97_image_13.png" width="640" height="261" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></p>

<p>Assuming the same Customer and Observable classes defined above,
and the same XAML UI, the following code in the code-behind will
throw that exception.</p>

<pre class="brush: csharp;">
private void ChangeNameFromSecondThread_Click(object sender, RoutedEventArgs e)<br />
{<br />
    Thread t = new Thread((o) =&gt;<br />
        {<br />
            _vm.CurrentCustomer.FirstName = "UpdatedFromSecondThread";<br />
        });<br />
<br />
    t.Start();<br />
}
</pre>

<p>The exception doesn't happen when you set the property value;
that's perfectly acceptable. It happens here, at the highlighted
line:</p>

<pre class="brush: csharp; highlight: [4];">
protected void NotifyPropertyChanged(string propertyName)<br />
{<br />
    if (PropertyChanged != null)<br />
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));<br />
}
</pre>

<p>So, what are the options for working around this? Let's consider
two common approaches.</p>

<h5>Approach 1</h5>

<p>The first approach is to do the whole property change from the
UI thread. To do this, simply wrap the property set code with a
call to the dispatcher. You can use either the Dispatcher object,
or if you keep a copy of the SynchronizationContext around, use
that.</p>

<p><img src="http://10rem.net/media/82282/Windows-Live-Writer_Threading-Considerations-for-Binding-in-_EF97_image_22.png" width="640" height="261" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></p>

<p>Here's some example code which implements this. The code looks a
bit silly because I'm forcing a background thread. However, pretend
that the background thread is a given and you need to work from it
(again, the callback from a network call or something.)</p>

<pre class="brush: csharp;">
private void ChangeNameFromSecondThread_Click(object sender, RoutedEventArgs e)<br />
{<br />
    Thread t = new Thread((o) =&gt;<br />
    {<br />
        Deployment.Current.Dispatcher.BeginInvoke(() =&gt;<br />
            {<br />
                _vm.CurrentCustomer.FirstName = "UpdatedFromSecondThread";<br />
            });<br />
    });<br />
<br />
    t.Start();<br />
}
</pre>

<p>This approach works well, but requires the calling code to
handle all the dispatching. If you have a number of properties to
change in different bits of code, it gets a bit cumbersome. Let's
look at another approach.</p>

<h5>Approach 2</h5>

<p>The real problem is the property change notification, so the the
second approach is to dispatch just the change notification to the
UI thread.</p>

<p><a
href="http://10rem.net/media/82287/Windows-Live-Writer_Threading-Considerations-for-Binding-in-_EF97_image_24.png"
 target="_blank"><img src="http://10rem.net/media/82292/Windows-Live-Writer_Threading-Considerations-for-Binding-in-_EF97_image_thumb_8.png" width="640" height="261" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></a></p>

<p>You can put this code into the Observable base class in order to
avoid repeating it throughout all your classes.</p>

<pre class="brush: csharp;">
// Code-behind<br />
// ----------------------------------------------<br />
<br />
<br />
// this version throws an exception if the Observable base class isn't doing thread checking<br />
private void ChangeNameFromSecondThread_Click(object sender, RoutedEventArgs e)<br />
{<br />
    Thread t = new Thread((o) =&gt;<br />
        {<br />
            _vm.CurrentCustomer.FirstName = "UpdatedFromSecondThread";<br />
        });<br />
<br />
    t.Start();<br />
}<br />
<br />
<br />
// Observable<br />
// ----------------------------------------------<br />
<br />
<br />
using System.ComponentModel;<br />
using System.Windows;<br />
<br />
namespace SilverlightThreadingExample<br />
{<br />
    public class Observable : INotifyPropertyChanged<br />
    {<br />
        public event PropertyChangedEventHandler PropertyChanged;<br />
<br />
        protected void NotifyPropertyChanged(string propertyName)<br />
        {<br />
            if (PropertyChanged != null)<br />
            {<br />
                if (Deployment.Current.Dispatcher.CheckAccess())<br />
                {<br />
                    PropertyChanged(this, new PropertyChangedEventArgs(propertyName));<br />
                }<br />
                else<br />
                {<br />
                    Deployment.Current.Dispatcher.BeginInvoke(() =&gt;<br />
                    {<br />
                        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));<br />
                    });<br />
                }<br />
            }<br />
        }<br />
    }<br />
}
</pre>

<p>Note how I first check to see if we have access to the UI thread
using the CheckAccess call. If we do, there's no reason to incur
the overhead and delay of a dispatcher call. However, if we are
running on the background thread, then the call is dispatched to
the UI thread. In either case, we avoid the errors cause by
cross-thread property change notification.</p>

<p>Next up: Collections</p>

<h4>Populating an ObservableCollection from a networking return
call</h4>

<p>A more robust Observable base class like this won't help with
collection change notification (WPF 4.5 has a great solution for
that using BindingOperations.EnableCollectionSynchronization, but
unfortunately Silverlight does not).</p>

<p>Most applications make networking calls to get information from
some resource on an intranet or out on the web. In Silverlight (and
WPF), it's common practice to populate an ObservableCollection with
the results from those calls. The ObservableCollection class is
nice because it implements INotifyCollectionChanged and raises an
event whenever items are added to or deleted from the collection,
or when the collection is cleared. It's this notification that
enables the various items controls and grids in the UI to stay in
sync with the items in the collection.</p>

<p><img src="http://10rem.net/media/82297/Windows-Live-Writer_Threading-Considerations-for-Binding-in-_EF97_image_16.png" width="640" height="261" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></p>

<p>This version is very similar to what we saw with individual
properties earlier. That's because, it's really the same problem:
we're trying to notify the binding system across threads.</p>

<pre class="brush: csharp;">
private void AddCustomerSecond_Click(object sender, RoutedEventArgs e)<br />
{<br />
    Thread t = new Thread((o) =&gt;<br />
    {<br />
        var cust = new Customer() { FirstName = "AddedFromSecondThread" };<br />
        _vm.Customers.Add(cust);<br />
    });<br />
<br />
    t.Start();<br />
}
</pre>

<p>Note that the problem exists regardless of where you actually
create the customer. For example, this code will also fail:</p>

<pre class="brush: csharp;">
private void AddCustomerSecond_Click(object sender, RoutedEventArgs e)<br />
{<br />
    var cust = new Customer() { FirstName = "AddedFromSecondThread" };<br />
<br />
    Thread t = new Thread((o) =&gt;<br />
    {<br />
        _vm.Customers.Add(cust);<br />
    });<br />
<br />
    t.Start();<br />
}
</pre>

<p>The reason is, again, it's not the object access that is causing
the cross-thread exception, it's the collection changed
notification that's full of hate here.</p>

<p>So, how do you get around this? Unless you want to create your
own ObservableCollection type class for Silverlight, you'll need to
dispatch all collection add calls. Luckily, you'll typically have
fewer of these scattered throughout the application, so it's not
quite so onerous.</p>

<p><img src="http://10rem.net/media/82302/Windows-Live-Writer_Threading-Considerations-for-Binding-in-_EF97_image_27.png" width="640" height="261" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></p>

<p>The code to implement this is just another easy call to the
dispatcher (or SynchronizationContext, if you prefer).</p>

<pre class="brush: csharp;">
private void AddCustomerSecond_Click(object sender, RoutedEventArgs e)<br />
{<br />
    // you can create customer on any thread<br />
    var cust = new Customer() { FirstName = "AddedFromSecondThread" };<br />
<br />
    Thread t = new Thread((o) =&gt;<br />
        {<br />
<br />
            // dispatch to UI thread to add it to the collection. You can't<br />
            // access the observable collection x-thread<br />
            Deployment.Current.Dispatcher.BeginInvoke(() =&gt;<br />
                {<br />
                    _vm.Customers.Add(cust);<br />
                });<br />
        });<br />
<br />
    t.Start();<br />
}
</pre>

<p>If you're going to run from an unknown state, be sure to call
CheckAccess to see if you really need to do the dispatching. In
this case, I know I'm always going to be on a background thread, so
I don't bother.</p>

<h3>Summary</h3>

<p>The intent here was to show a few of the common threading
pitfalls in Silverlight (and WPF) applications, specifically in the
context of change notification. In most code, it's easy to tell
when you're accessing objects cross-thread, but change notification
is a somewhat behind the scenes operation, so it's not always
obvious.</p>

<p>For property change notification, the solutions were:</p>

<ul>
<li>Dispatch the entire property change operation to the UI
thread</li>

<li>Update the NotifyPropertyChanged code to check to see which
thread it's running on, and then dispatch the event as
appropriate</li>
</ul>

<p>Either way works, but I prefer the update to the
NotifyPropertyChanged method.</p>

<p>For collection change notifications in Silverlight, the
solutions are:</p>

<ul>
<li>Create (or find) an implementation of ObservableCollection
which does the cross-thread checking. The reason this isn't
built-in is change notification happens often, and dispatching each
and every change notification can be a real performance drain.
That's also why WPF has a separate and optimized solution. You'd
need to enable batching to avoid the overhead of hundreds of
dispatch calls.</li>

<li>Dispatch the entire collection update when you're running on a
background thread.</li>
</ul>

<p>In contrast to the property change notifications, for collection
change, I prefer to dispatch the entire call. If you're adding 1
object or 100, you'll still get only one dispatch call, so
performance is better.</p>

<p>The Task Parallel Library in WPF, and the subset of it in
Silverlight also offer some alternative approaches to handling
cross-thread work. Similarly, the async and await keywords in .NET
4.5 and Windows 8 XAML can also come into play. More on those in
the future.</p>
]]></description></item><item><title>Creating a Custom Markup Extension in WPF (and soon, Silverlight)</title><author>Pete Brown	</author><link>http://10rem.net/blog/2011/03/09/creating-a-custom-markup-extension-in-wpf-and-soon-silverlight</link><pubDate>Wed, 09 Mar 2011 05:15:07 GMT</pubDate><guid>http://10rem.net/blog/2011/03/09/creating-a-custom-markup-extension-in-wpf-and-soon-silverlight</guid><description><![CDATA[ 
<p>WPF currently, and <a
href="http://johnpapa.net/silverlight/silverlight5features/">Silverlight
in v5</a>, enables you to create your own custom markup extensions.
Markup extensions are those little strings in XAML that are
typically (but not always) enclosed in {curly braces} which, as the
name implies, add new functionality to XAML. The most commonly used
markup extensions are the {StaticResource}, {TemplateBinding}, and
{Binding} extensions.</p>

<p>Creating your own markup extensions is a nice way to integrate
your view of the world into the toolset. They're particularly
popular with MVVM and similar toolkits.</p>

<blockquote>
<p>This article is, in part, an excerpt from early work in
Silverlight 5 in Action, the revised edition of <a
href="http://manning.com/pbrown">Silverlight 4 in Action</a>. SL5
in Action is due out by the end of 2011, and will have a MEAP
(early access bits) around the time of the first public developer
release of Silverlight 5.</p>
</blockquote>

<h3>Creating a Simple Markup Extension</h3>

<p>There's not much ceremony to creating a markup extension. The
amount of effort required is directly proportional to the
complexity of what you're trying to do. For example:</p>

<pre class="brush: csharp;">
public class HelloExtension : MarkupExtension<br />
{<br />
  public HelloExtension() { }<br />
<br />
  public override object ProvideValue(<br />
                  IServiceProvider serviceProvider)<br />
  {<br />
    return "Hello";<br />
  }<br />
}<br />
</pre>

<p>As shown in this example, to create a markup extension, you need
only inherit from MarkupExtension and override the ProvideValue
method. The empty constructor is necessary for use in XAML,
specifically when you include additional parameterized
constructors.</p>

<p>When you use the markup extension, you must declare the
namespace as explained in section 2.1.2 (of Silverlight 4/5 in
Action), and use the class name in your XAML. For example, the
following XAML uses the HelloExtension markup extension we just
created.</p>

<pre class="brush: xml;">
&lt;Grid xmlns:ext="clr-namespace:CustomMarkupExtensions"&gt;<br />
  &lt;TextBlock Text="{ext:Hello}" /&gt;<br />
&lt;/Grid&gt;<br />
<br />
</pre>

<p>Because we followed the convention of naming our markup
extension with the suffix "Extension", we refer to it simply as
"Hello" not "HelloExtension". The convention is helpful, but not
required. When run, the result</p>

<p><a
href="http://10rem.net/media/74255/Windows-Live-Writer_Creating-a-Custom-Markup-Extension-in-WP_C66_image_2.png"
 target="_blank"><img src="http://10rem.net/media/74260/Windows-Live-Writer_Creating-a-Custom-Markup-Extension-in-WP_C66_image_thumb.png" width="500" height="343" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></a></p>

<p>One interesting thing is that markup extensions can be blown out
using property element syntax. So, you could use the curly braces
as shown above, or you could get the same effect by writing it this
way:</p>

<pre class="brush: xml;">
&lt;Grid xmlns:ext="clr-namespace:CustomMarkupExtensions"&gt;<br />
  &lt;TextBlock&gt;<br />
    &lt;TextBlock.Text&gt;<br />
      &lt;ext:Hello /&gt;<br />
    &lt;/TextBlock.Text&gt;<br />
  &lt;/TextBlock&gt;<br />
&lt;/Grid&gt;
</pre>

<p>This can be important for some scenarios where you need finer
control over what you pass in, as we'll see later.</p>

<p>That was a super-simple example, but shows how little you need
to do to create a markup extension. Next, we'll look at how to make
an extension that takes in a parameter or two.</p>

<h3>Creating a Markup Extension with Support for Parameters</h3>

<p>Typically, markup extensions will be more complex and include
the ability to accept parameters. As we previously saw, the
built-in examples such as Binding, take in a number of discrete
parameters which are used to provide key values as well as to alter
their behavior.</p>

<p>This example shows how to create an interesting markup extension
which will always return the maximum of two provided values.</p>

<pre class="brush: csharp;">
public class MaxValueExtension : MarkupExtension<br />
{<br />
  public MaxValueExtension() { }<br />
<br />
  public MaxValueExtension(object value1, object value2)<br />
  {<br />
    Value1 = value1;<br />
    Value2 = value2;<br />
  }<br />
<br />
  [ConstructorArgument("value1")] <br />
  public object Value1 { get; set; }<br />
<br />
  [ConstructorArgument("value2")] <br />
  public object Value2 { get; set; }<br />
<br />
  public override object ProvideValue(<br />
                         IServiceProvider serviceProvider)<br />
  {<br />
    if (Value1 is IComparable &amp;&amp; Value2 is IComparable)<br />
    {<br />
      IComparable val1 = Value1 as IComparable;<br />
      IComparable val2 = Value2 as IComparable;<br />
<br />
      if (val1.CompareTo(val2) &gt;= 0)<br />
        return Value1.ToString(); <br />
      else<br />
        return Value2.ToString(); <br />
    }<br />
    else<br />
    {<br />
      return string.Empty;<br />
    }<br />
  }<br />
}<br />
</pre>

<p>Compared to the previous example, this adds a few new elements.
First, we have a constructor accepting two parameters. Those two
parameters are also provided as discrete properties. Note that the
properties have been marked up so they map to the parameters - this
is used by XAML serialization and, while not required, is a good
practice.</p>

<p>Arguably, there's at least one cheat in this code: I coerce the
final returned value to a string. That limits its usefulness for
anything other than a Text or Content property. However, it keeps
this example simple.</p>

<p>To use the markup extension, the syntax is similar. There's a
subtle bug in this approach, however, which I'll explain after the
example.</p>

<pre class="brush: xml;">
&lt;Grid xmlns:ext="clr-namespace:CustomMarkupExtensions"&gt;<br />
  &lt;TextBlock Text="{ext:MaxValue Value1=200,Value2=25}" /&gt;<br />
&lt;/Grid&gt;<br />
<br />
</pre>

<p>In this example, you'd expect the TextBlock to display 200, but
it displays 25. This is because the values, in the absence of any
other type cues, are treated as strings. One way to force them to
be treated as numbers is to break the statement out using the
property element syntax described earlier. The next example shows
the verbose approach to using the markup extension</p>

<pre class="brush: xml;">
&lt;Grid xmlns:ext="clr-namespace:CustomMarkupExtensions"<br />
      xmlns:sys="clr-namespace:System;assembly=mscorlib"&gt;<br />
  &lt;TextBlock&gt;<br />
    &lt;TextBlock.Text&gt;<br />
      &lt;ext:MaxValue&gt;<br />
        &lt;ext:MaxValueExtension.Value1&gt;<br />
          &lt;sys:Int32&gt;200&lt;/sys:Int32&gt;<br />
        &lt;/ext:MaxValueExtension.Value1&gt;<br />
        &lt;ext:MaxValueExtension.Value2&gt;<br />
          &lt;sys:Int32&gt;25&lt;/sys:Int32&gt;<br />
        &lt;/ext:MaxValueExtension.Value2&gt;<br />
      &lt;/ext:MaxValue&gt;<br />
    &lt;/TextBlock.Text&gt;<br />
  &lt;/TextBlock&gt;<br />
&lt;/Grid&gt;<br />
</pre>

<p>This markup shows the expanded approach. While this is
significantly longer than the previous example, it does provide
complete control over the parameters. Note also that the MaxValue
markup extension uses its full name MaxValueExtension when
referencing its own parameters.</p>

<p><a
href="http://10rem.net/media/74265/Windows-Live-Writer_Creating-a-Custom-Markup-Extension-in-WP_C66_image_4.png"
 target="_blank"><img src="http://10rem.net/media/74270/Windows-Live-Writer_Creating-a-Custom-Markup-Extension-in-WP_C66_image_thumb_1.png" width="333" height="185" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></a></p>

<p>With the types correctly specified, it works as expected. Of
course, you could build intelligence into your markup extension or
use other ways of forcing the types. You could even create a markup
extension that always returns an integer and use that as a
parameter to your MaxValue extension.</p>

<p>Let's go the approach of adding some brains to our markup
extension.</p>

<h3>Creating a Markup Extension with Type Casting Support</h3>

<p>So far, we've done nothing with the IServiceProvider parameter
to the ProvideValue function. That object provides some interesting
information about the target that this extension is going to
populate. The IServiceProvider interface includes a GetService
function which can return an IProvideValueTarget. Using that
interface, you can access the target object and property, get
property/type information from them, and set the property value
directly.</p>

<p>In our case, we want to make sure that if we pass in two ints,
but plan to use the result in a TextBlock, that the resulting int
is converted to a string. If you leave the conversion out, you will
get an error at runtime when you specify the types using, for
example, this syntax (same approach as the earlier example):</p>

<pre class="brush: xml;">
&lt;Grid xmlns:ext="clr-namespace:CustomMarkupExtensions"<br />
        xmlns:sys="clr-namespace:System;assembly=mscorlib"&gt;<br />
    &lt;TextBlock&gt;<br />
        &lt;TextBlock.Text&gt;<br />
            &lt;ext:MaxValue&gt;<br />
                &lt;ext:MaxValueExtension.Value1&gt;<br />
                    &lt;sys:Int32&gt;100&lt;/sys:Int32&gt;<br />
                &lt;/ext:MaxValueExtension.Value1&gt;<br />
                &lt;ext:MaxValueExtension.Value2&gt;<br />
                    &lt;sys:Int32&gt;90&lt;/sys:Int32&gt;<br />
                &lt;/ext:MaxValueExtension.Value2&gt;<br />
            &lt;/ext:MaxValue&gt;     <br />
        &lt;/TextBlock.Text&gt;<br />
    &lt;/TextBlock&gt;<br />
&lt;/Grid&gt;
</pre>

<p>As mentioned previously, you normally get strings as parameters
unless you break it out and get explicit with what you're passing
in. Once you do that, you have to build conversion smarts into your
markup extension. Here's the full markup extension with the type
conversion logic built in.</p>

<pre class="brush: csharp;">
using System;<br />
using System.Windows.Markup;<br />
using System.Windows;<br />
using System.Reflection;<br />
<br />
namespace CustomMarkupExtensions<br />
{<br />
    // totally optional. I have the return type here just so you know<br />
    // it's possible. With a return type of object, you wouldn't normally<br />
    // include the return type attribute<br />
    [MarkupExtensionReturnType(typeof(object))]<br />
    public class MaxValueExtension : MarkupExtension<br />
    {<br />
        public MaxValueExtension() { }<br />
<br />
        public MaxValueExtension(object value1, object value2)<br />
        {<br />
            Value1 = value1;<br />
            Value2 = value2;<br />
        }<br />
<br />
        [ConstructorArgument("value1")]<br />
        public object Value1 { get; set; }<br />
<br />
        [ConstructorArgument("value2")]<br />
        public object Value2 { get; set; }<br />
<br />
        private object GetMaxValue()<br />
        {<br />
            if (Value1 is IComparable &amp;&amp; Value1 is IComparable)<br />
            {<br />
                if (((IComparable)Value1).CompareTo(Value2) &gt;= 0)<br />
                    return Value1;<br />
                else<br />
                    return Value2;<br />
            }<br />
            else<br />
            {<br />
                // use val1<br />
                return Value1;<br />
            }<br />
        }<br />
<br />
        public override object ProvideValue(IServiceProvider serviceProvider)<br />
        {<br />
            if (serviceProvider == null)<br />
                return null;<br />
<br />
            // get the target of the extension from the IServiceProvider interface<br />
            IProvideValueTarget ipvt =<br />
                (IProvideValueTarget)serviceProvider.GetService(typeof(IProvideValueTarget));<br />
         <br />
            DependencyObject targetObject = ipvt.TargetObject as DependencyObject;<br />
<br />
            object val = GetMaxValue();<br />
<br />
            if (ipvt.TargetProperty is DependencyProperty)<br />
            {<br />
                // target property is a DP<br />
                DependencyProperty dp = ipvt.TargetProperty as DependencyProperty;<br />
<br />
                if (val is IConvertible)<br />
                {<br />
                    val = Convert.ChangeType(val, dp.PropertyType);<br />
                }<br />
            }<br />
            else<br />
            {<br />
                // target property is not a DP, it's PropertyInfo instead.<br />
                PropertyInfo info = ipvt.TargetProperty as PropertyInfo;<br />
<br />
                if (val is IConvertible)<br />
                {<br />
                    val = Convert.ChangeType(val, info.PropertyType);<br />
                }<br />
            }<br />
<br />
            return val;<br />
        }<br />
    }<br />
}
</pre>

<p>This example is more complex, but if you break down the code,
there's nothing magical going on here. Inside ProvideValue, I check
to see if we have a DependencyProperty or a regular property.&nbsp;
Based on the type of property we're accessing, I get the
PropertyType and then, if the type is convertible, call
Convert.ChangeType to handle the type conversion.</p>

<p>MarkupExtensions can provide some interesting functionality to
your XAML. Of course, you'll want to temper this with testability
concerns (it's harder to test this than logic in your viewmodel),
but it can get you out of some scrapes, and otherwise clean up
nasty glue/utility code you may need to write in your
code-behind.</p>

<p><strong>This was written against and tested on WPF4. I haven't
tested this on Silverlight 5, so if you're reading this in the
Silverlight 5 timeframe, your mileage may vary.</strong></p>
]]></description></item><item><title>Asynchronous Web and Network Calls on the Client in WPF (and Silverlight and .NET in general)</title><author>Pete Brown	</author><link>http://10rem.net/blog/2011/02/17/asynchronous-web-and-network-calls-on-the-client-in-wpf-and-silverlight-and-net-in-general</link><pubDate>Fri, 18 Feb 2011 00:43:01 GMT</pubDate><guid>http://10rem.net/blog/2011/02/17/asynchronous-web-and-network-calls-on-the-client-in-wpf-and-silverlight-and-net-in-general</guid><description><![CDATA[ 
<p>An asynchronous network call is one in which you fire off a
method and don't block the thread while waiting for it to return.
This introduces some complexities since you have to somehow be
notified of the success or failure of the call, and need to somehow
retrieve the results.</p>

<p>Silverlight developers are used to making asynchronous network
calls because that's all the stack has supported since first
released. However, WPF developers can benefit from a little async
code in their applications to help make things a bit more
responsive.</p>

<h3>Solution Setup</h3>

<p>I created a solution into which I put a regular WPF Windows
application and an empty ASP.NET Web application.</p>

<h4>Services Project</h4>

<p>Into the ASP.NET Web Application, I added a "Silverlight-enabled
WCF Service". Why that template? It's a super simple approach to
creating WCF services that act like regular old SOAP services. It
keeps the example easy to follow.</p>

<p>The service is in a Services subfolder on the web project and is
named CustomerService.svc. Here's the code:</p>

<pre class="brush: csharp;">
using System;<br />
using System.Linq;<br />
using System.Runtime.Serialization;<br />
using System.ServiceModel;<br />
using System.ServiceModel.Activation;<br />
using System.Collections.Generic;<br />
<br />
namespace WebServicesSite.Services<br />
{<br />
    [ServiceContract(Namespace = "")]<br />
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]<br />
    public class CustomerService<br />
    {<br />
        [OperationContract]<br />
        public IList&lt;Customer&gt; GetCustomers()<br />
        {<br />
            List&lt;Customer&gt; results = new List&lt;Customer&gt;();<br />
<br />
            results.Add(new Customer() { LastName = "Brown", FirstName = "Pete" });<br />
            results.Add(new Customer() { LastName = "Stagner", FirstName = "Joe" });<br />
            results.Add(new Customer() { LastName = "Liberty", FirstName = "Jesse" });<br />
            results.Add(new Customer() { LastName = "Galloway", FirstName = "Jon" });<br />
<br />
            return results;<br />
        }<br />
<br />
      <br />
    }<br />
}
</pre>

<p>In the same folder on the ASP.NET Service project, I added a
class named "Customer":</p>

<pre class="brush: csharp;">
namespace WebServicesSite.Services<br />
{<br />
    public class Customer<br />
    {<br />
        public string FirstName { get; set; }<br />
        public string LastName { get; set; }<br />
    }<br />
}
</pre>

<p>Once you have the service set up, you'll want to fix the web
project's port just to ensure that you don't hang the service and
get stuck with a new port the next time you run. That results in
your app not finding the service and can be hard to debug unless
you know what you're looking for.</p>

<p><a
href="http://10rem.net/media/74066/Windows-Live-Writer_Asynchronous-Web-Calls-in-WPF_FB6_image_2.png"
 target="_blank"><img src="http://10rem.net/media/74071/Windows-Live-Writer_Asynchronous-Web-Calls-in-WPF_FB6_image_thumb.png" width="520" height="307" alt="image" border="0" style="background-image: none; border-right-width: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px"/></a></p>

<p>The actual port number isn't that important; I used the default.
Just be sure to set to Specific port to lock in that port number.
<strong><em>Silverlight developers: this isn't a bad idea when
working on your own web services in your
projects.</em></strong></p>

<p>Next, add a service reference from your WPF project to the new
service in the ASP.NET project (be sure to build the solution
first). I named the namespace "Services"</p>

<p><a
href="http://10rem.net/media/74076/Windows-Live-Writer_Asynchronous-Web-Calls-in-WPF_FB6_image_4.png"
 target="_blank"><img src="http://10rem.net/media/74081/Windows-Live-Writer_Asynchronous-Web-Calls-in-WPF_FB6_image_thumb_1.png" width="500" height="410" alt="image" border="0" style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px"/></a></p>

<p>Before clicking "OK", click the "Advanced…" button and select
the option to generate the asynchronous client operations. In
Silverlight, this is on by default as there's no other option. In
WPF, however, async operations are less typical.</p>

<p><a
href="http://10rem.net/media/74086/Windows-Live-Writer_Asynchronous-Web-Calls-in-WPF_FB6_image_6.png"
 target="_blank"><img src="http://10rem.net/media/74091/Windows-Live-Writer_Asynchronous-Web-Calls-in-WPF_FB6_image_thumb_2.png" width="481" height="448" alt="image" border="0" style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px"/></a></p>

<p>If you received an error downloading the metadata, <strong>you
need to successfully build the web project first</strong>.</p>

<p>Next, we'll need to build some basic UI.</p>

<h4>User Interface</h4>

<p>I used the designer in Visual studio 2010 to create a dead
simple user interface. (In Xaml, I changed Name to x:Name as is my
habit), and added a simple item template to the ListBox. Here's the
markup:</p>

<pre class="brush: xml;">
&lt;Window x:Class="WpfAsyncExample.MainWindow"<br />
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"<br />
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"<br />
        Title="Async Service Example"<br />
        Height="350"<br />
        Width="525"&gt;<br />
    &lt;Grid&gt;<br />
        &lt;Button Content="Call Service"<br />
                x:Name="CallService"<br />
                Height="23"<br />
                HorizontalAlignment="Left"<br />
                Margin="12,12,0,0"<br />
                VerticalAlignment="Top"<br />
                Width="75"<br />
                Click="CallService_Click" /&gt;<br />
        &lt;ListBox HorizontalAlignment="Left"<br />
                 Margin="12,51,0,12"<br />
                 x:Name="CustomerList"<br />
                 Width="479"&gt;<br />
            &lt;ListBox.ItemTemplate&gt;<br />
                &lt;DataTemplate&gt;<br />
                    &lt;StackPanel Orientation="Horizontal"&gt;<br />
                        &lt;TextBlock Text="{Binding LastName}" /&gt;<br />
                        &lt;TextBlock Text=", " /&gt;<br />
                        &lt;TextBlock Text="{Binding FirstName}" /&gt;<br />
                    &lt;/StackPanel&gt;<br />
                &lt;/DataTemplate&gt;<br />
            &lt;/ListBox.ItemTemplate&gt;<br />
        &lt;/ListBox&gt;<br />
    &lt;/Grid&gt;<br />
&lt;/Window&gt;
</pre>

<p>The first approach we'll look at is the simple event-based
approach. So double-click that button and create an event handler
we can use in the remaining examples.</p>

<h3>The Event Approach</h3>

<p>When it's possible to use the event approach, this is by far the
easiest way to handle asynchronous calls, and is the approach used
most often in Silverlight code as well.</p>

<pre class="brush: csharp;">
private void CallService_Click(object sender, RoutedEventArgs e)<br />
{<br />
    var client = new Services.CustomerServiceClient();<br />
<br />
    client.GetCustomersCompleted += (s, ev) =&gt;<br />
        {<br />
            CustomerList.ItemsSource = ev.Result;<br />
        };<br />
<br />
    client.GetCustomersAsync();<br />
}
</pre>

<p>To keep the code even tighter, I used an anonymous delegate and
lambda expression to set up the event handler. You could also break
it apart into a separate method, but I personally find that muddies
the code.</p>

<p>The event approach is nice because you don't typically need to
worry about threading and marshaling a result back to the UI
thread; that's taken care of for you.</p>

<p>The next approach is a bit more flexible, but is also more
complex.</p>

<h3>The Callback Approach</h3>

<p>Another common approach is the callback approach. I often think
of this as the bare-bones method, as it is definitely a level or
two lower than the event approach. However, you gain some
additional flexibility in that there are no threading assumptions
made, and you can pass around your own state objects.</p>

<pre class="brush: csharp;">
private void CallService_Click(object sender, RoutedEventArgs e)<br />
{<br />
    // we'll need this to update the UI<br />
    SynchronizationContext context = SynchronizationContext.Current;<br />
<br />
    var client = new Services.CustomerServiceClient();<br />
<br />
    // this can be anything: a custom class or whatever you need<br />
    // to track state from the call to the response<br />
    CustomerRequestState requestState = new CustomerRequestState();<br />
    requestState.Client = client;<br />
    requestState.Context = context;<br />
<br />
    IAsyncResult asyncResult = client.BeginGetCustomers(<br />
        new AsyncCallback(ResponseCallback), requestState);<br />
}<br />
<br />
private void ResponseCallback(IAsyncResult asyncResult)<br />
{<br />
    CustomerRequestState asyncState = asyncResult.AsyncState as CustomerRequestState;<br />
<br />
    Customer[] customers = asyncState.Client.EndGetCustomers(asyncResult);<br />
<br />
    // you can't just do this, as you'll get a cross-thread access error<br />
    //CustomerList.ItemsSource = customers;<br />
<br />
    // use SynchronizationContext and an anonymous delegate<br />
    // to update the listbox in the UI<br />
    asyncState.Context.Post((o) =&gt;<br />
        { CustomerList.ItemsSource = customers; }, null);<br />
<br />
}
</pre>

<p>To make this work, we'll also need to create a state object to
hold the bits we want to pass from the call to the response
loading. I decided to track the calling WCF client (we'll need a
reference to that), the synchronization context, and an arbitrary
bit of data I don't actually use. Your own object can contain as
little or as much as you need.</p>

<pre class="brush: csharp;">
namespace WpfAsyncExample<br />
{<br />
    class CustomerRequestState<br />
    {<br />
        public string AnythingYouWant { get; set; }<br />
        public CustomerServiceClient Client { get; set; }<br />
        public SynchronizationContext Context { get; set; }<br />
    }<br />
}
</pre>

<p>Now, I mentioned that I am passing around a
SynchronizationContext. That object allows us to make calls back on
the original calling thread, in this case, the UI thread. We need
to be able to marshal calls to that thread in order to update the
user interface. If you try and update the UI from a non-UI thread,
you'll get a cross-thread access exception.</p>

<p><strong>Now, to keep things simple and understandable in the
above code, I haven't done any error handling or proper disposal of
objects. Make sure you do that in your production
code.</strong></p>

<p>The final approach we'll look at builds upon what we've seen so
far, but makes it easier to do things like chain successive calls
without all the cruft you'd normally use.</p>

<h3>Using Reactive Extensions</h3>

<p>The final example uses an additional library knows as "Reactive
Extensions for .NET" or "Rx". This library does a ton of things to
help handle asynchronous operations without making your code into
an unintelligible bowl of calls and response callbacks.</p>

<p>First, get Reactive Extensions. You can either <a
href="http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx">download
it from the main site</a>, or better yet, use NuGet to add it
directly to your project. The NuGet approach will save you a ton of
time. <a
href="http://10rem.net/blog/2011/02/10/nuget-for-wpf-and-silverlight-developers">
Learn how to use NuGet in your WPF projects here</a>.</p>

<pre class="brush: plain;">
PM&gt; install-package Rx-All<br />
'Rx-Core (≥ 1.0.2856.0)' not installed. Attempting to retrieve dependency from source...<br />
Done<br />
'Rx-AsyncLinq (≥ 1.0.2856.0)' not installed. Attempting to retrieve dependency from source...<br />
Done<br />
'Rx-Interactive (≥ 1.0.2856.0)' not installed. Attempting to retrieve dependency from source...<br />
Done<br />
'Rx-Main (≥ 1.0.2856.0)' not installed. Attempting to retrieve dependency from source...<br />
Done<br />
'Rx-ClientProfile (≥ 1.0.2856.0)' not installed. Attempting to retrieve dependency from source...<br />
Done<br />
'Rx-ExtendedProfile (≥ 1.0.2856.0)' not installed. Attempting to retrieve dependency from source...<br />
Done<br />
'Rx-Testing (≥ 1.0.2856.0)' not installed. Attempting to retrieve dependency from source...<br />
Done<br />
You are downloading Rx-Core from Microsoft Corporation, the license agreement to which is available at http://go.microsoft.com/fwlink/?LinkID=186234. Check the package for additional dependencies, which may come with their own license agreement(s). Your use of the package and dependencies constitutes your acceptance of their license agreements. If you do not accept the license agreement(s), then delete the relevant components from your device.<br />
Successfully installed 'Rx-Core 1.0.2856.0'<br />
You are downloading Rx-AsyncLinq from Microsoft Corporation, the license agreement to which is available at http://go.microsoft.com/fwlink/?LinkID=186234. Check the package for additional dependencies, which may come with their own license agreement(s). Your use of the package and dependencies constitutes your acceptance of their license agreements. If you do not accept the license agreement(s), then delete the relevant components from your device.<br />
Successfully installed 'Rx-AsyncLinq 1.0.2856.0'<br />
You are downloading Rx-Interactive from Microsoft Corporation, the license agreement to which is available at http://go.microsoft.com/fwlink/?LinkID=186234. Check the package for additional dependencies, which may come with their own license agreement(s). Your use of the package and dependencies constitutes your acceptance of their license agreements. If you do not accept the license agreement(s), then delete the relevant components from your device.<br />
Successfully installed 'Rx-Interactive 1.0.2856.0'<br />
You are downloading Rx-Main from Microsoft Corporation, the license agreement to which is available at http://go.microsoft.com/fwlink/?LinkID=186234. Check the package for additional dependencies, which may come with their own license agreement(s). Your use of the package and dependencies constitutes your acceptance of their license agreements. If you do not accept the license agreement(s), then delete the relevant components from your device.<br />
Successfully installed 'Rx-Main 1.0.2856.0'<br />
You are downloading Rx-ClientProfile from Microsoft Corporation, the license agreement to which is available at http://go.microsoft.com/fwlink/?LinkID=186234. Check the package for additional dependencies, which may come with their own license agreement(s). Your use of the package and dependencies constitutes your acceptance of their license agreements. If you do not accept the license agreement(s), then delete the relevant components from your device.<br />
Successfully installed 'Rx-ClientProfile 1.0.2856.0'<br />
You are downloading Rx-ExtendedProfile from Microsoft Corporation, the license agreement to which is available at http://go.microsoft.com/fwlink/?LinkID=186234. Check the package for additional dependencies, which may come with their own license agreement(s). Your use of the package and dependencies constitutes your acceptance of their license agreements. If you do not accept the license agreement(s), then delete the relevant components from your device.<br />
Successfully installed 'Rx-ExtendedProfile 1.0.2856.0'<br />
You are downloading Rx-Testing from Microsoft Corporation, the license agreement to which is available at http://go.microsoft.com/fwlink/?LinkID=186234. Check the package for additional dependencies, which may come with their own license agreement(s). Your use of the package and dependencies constitutes your acceptance of their license agreements. If you do not accept the license agreement(s), then delete the relevant components from your device.<br />
Successfully installed 'Rx-Testing 1.0.2856.0'<br />
You are downloading Rx-All from Microsoft Corporation, the license agreement to which is available at http://go.microsoft.com/fwlink/?LinkID=186234. Check the package for additional dependencies, which may come with their own license agreement(s). Your use of the package and dependencies constitutes your acceptance of their license agreements. If you do not accept the license agreement(s), then delete the relevant components from your device.<br />
Successfully installed 'Rx-All 1.0.2856.0'<br />
Successfully added 'Rx-Core 1.0.2856.0' to WpfAsyncExample<br />
Successfully added 'Rx-AsyncLinq 1.0.2856.0' to WpfAsyncExample<br />
Successfully added 'Rx-Interactive 1.0.2856.0' to WpfAsyncExample<br />
Successfully added 'Rx-Main 1.0.2856.0' to WpfAsyncExample<br />
Successfully added 'Rx-ClientProfile 1.0.2856.0' to WpfAsyncExample<br />
Successfully added 'Rx-ExtendedProfile 1.0.2856.0' to WpfAsyncExample<br />
Successfully added 'Rx-Testing 1.0.2856.0' to WpfAsyncExample<br />
Successfully added 'Rx-All 1.0.2856.0' to WpfAsyncExample<br />
<br />
PM&gt;
</pre>

<p>While that added a bit more than we'll use in this example, you
can control exactly what you get by only installing those packages.
Rx-All was the easiest thing for me to do for this example. There
are more than a few ways we can use Rx here, so I'm going to
concentrate on just one: using the event approach.</p>

<pre class="brush: csharp;">
private void CallService_Click(object sender, RoutedEventArgs e)<br />
{<br />
    // we'll need the UI thread just like last time<br />
    SynchronizationContext context = SynchronizationContext.Current;<br />
<br />
    var client = new Services.CustomerServiceClient();<br />
<br />
    // Wait for the GetCustomersCompleted event to finish. When<br />
    // it finishes, get the results from the event and<br />
    // using the thread context from "context", set the<br />
    // customer listbox item source to the result<br />
    var o = Observable.FromEvent&lt;GetCustomersCompletedEventArgs&gt;(<br />
                                   client, "GetCustomersCompleted")<br />
        .ObserveOn(context)<br />
        .Select(result =&gt; result.EventArgs.Result)<br />
        .Subscribe(s =&gt; CustomerList.ItemsSource = s);<br />
          <br />
    // kick it off<br />
    client.GetCustomersAsync();<br />
}
</pre>

<p>The code here initially looks as complex as the previous
versions, or at least as complex as the event version. However, one
subtle difference is that it has provided a nice way for us to
chain additional dependent calls. For example, so you need to first
call to get a customer ID, then make a separate call to get all the
invoices for that customer. That could involve some pretty ugly
call chaining in either the event approach or the callback
approach. The Rx approach will allow you to more easily chain those
calls together.</p>

<p><a
href="http://10rem.net/media/74096/Windows-Live-Writer_Asynchronous-Web-Calls-in-WPF_FB6_image_8.png"
 target="_blank"><img src="http://10rem.net/media/74101/Windows-Live-Writer_Asynchronous-Web-Calls-in-WPF_FB6_image_thumb_3.png" width="551" height="378" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></a></p>

<p>When you run the application, in all three approaches, you
should see the results shown here. Of course, what I have presented
is a simple example. In a real application, both the effort and the
benefits are greater.</p>

<h3>Why is this even Necessary?</h3>

<p>Like many of the practices we follow, it's not strictly
necessary. However, if you want to have a better user experience,
using either a spawned thread or an async call for service calls
can help keep your UI responsive.</p>

<p>Using async network calls also helps make your code and skills
more compatible with Silverlight. <strong>All the code here is
compatible with Silverlight.</strong></p>

<p>Consider using async operations in your next desktop
application.</p>
]]></description></item><item><title>NuGet for WPF and Silverlight Developers</title><author>Pete Brown	</author><link>http://10rem.net/blog/2011/02/10/nuget-for-wpf-and-silverlight-developers</link><pubDate>Thu, 10 Feb 2011 22:38:45 GMT</pubDate><guid>http://10rem.net/blog/2011/02/10/nuget-for-wpf-and-silverlight-developers</guid><description><![CDATA[ 
<p>NuGet is package management system for .NET and Visual Studio.
It allows people to create simple packages that install files into
your projects, adds references etc. It makes it super simple to get
working components and even scaffolding into your application
without having to search your drive, manually find references,
resolve dependencies etc.</p>

<blockquote>
<p>NuGet is a Visual Studio extension that makes it easy to install
and update open source libraries and tools in Visual Studio.</p>

<p>When you use NuGet to install a package, it copies the library
files to your solution and automatically updates your project (add
references, change config files, etc). If you remove a package,
NuGet reverses whatever changes it made so that no clutter is
left.</p>
</blockquote>

<p>While NuGet is most popular with the ASP.NET crowd, it's growing
in popularity with Silverlight and WPF developers as well.
Recently, in response to a little prodding Scott Hanselman gave
both me and Tim, <a
href="http://timheuer.com/blog/archive/2011/02/10/silverlight-toolkit-available-on-nuget.aspx"
 target="_blank">Tim Heuer did the work to get the Silverlight
Toolkit on NuGet.</a> That's awesome :)</p>

<p>NuGet is a painless install that doesn't screw up other stuff.
It's a simple Visual Studio extension. Let's try it out.</p>

<h3>Step 1: Install NuGet</h3>

<p>Go to <a href="http://nuget.org">nuget.org</a> and click on the
giant "Install NuGet" button</p>

<p><a
href="http://10rem.net/media/73994/Windows-Live-Writer_NuGet-for-WPF-and-Silverlight-Developers_E449_image_2.png"
 target="_blank"><img src="http://10rem.net/media/73999/Windows-Live-Writer_NuGet-for-WPF-and-Silverlight-Developers_E449_image_thumb.png" width="520" height="266" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></a></p>

<p>NuGet comes as a nice Visual Studio Extension installer (.vsix).
Go ahead and open it and allow it to install into Visual Studio. It
takes about 3 seconds on my SSD :)</p>

<p><a
href="http://10rem.net/media/74004/Windows-Live-Writer_NuGet-for-WPF-and-Silverlight-Developers_E449_image_4.png"
 target="_blank"><img src="http://10rem.net/media/74009/Windows-Live-Writer_NuGet-for-WPF-and-Silverlight-Developers_E449_image_thumb_1.png" width="442" height="307" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></a></p>

<h3>Step 2: Find a Package</h3>

<p>There are two main modes of operation for NuGet: the dialog
approach and the command line approach. There's a great <a
href="http://nuget.codeplex.com/wikipage?title=Getting%20Started">Getting
Started tutorial</a> on the NuGet codeplex site, so I'll only cover
a subset of it here.</p>

<p>Let's see what's out there for WPF and Silverlight. We'll try
the command-line approach. Under the tools menu, open the Library
Package Manager (NuGet) Console</p>

<p><a
href="http://10rem.net/media/74014/Windows-Live-Writer_NuGet-for-WPF-and-Silverlight-Developers_E449_image_6.png"
 target="_blank"><img src="http://10rem.net/media/74019/Windows-Live-Writer_NuGet-for-WPF-and-Silverlight-Developers_E449_image_thumb_2.png" width="520" height="331" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></a></p>

<p>Once you see the Package Manager Console command prompt at the
bottom of your screen, type "get-package -remote" to list of the
available packages in the official NuGet Repository. In the current
release, it may truncate the list if it's too long (that's being
fixed today). In the mean time, let's try a little
filter/search.</p>

<p>Type "get-package -filter wpf" to see ones with the word WPF in
the ID or description. It returned this for me:</p>

<pre class="brush: plain;">
PM&gt; get-package -remote -filter wpf<br />
<br />
Id                                                                   Version                                                              Description                                                    <br />
--                                                                   -------                                                              -----------                                                    <br />
AvalonEdit                                                           4.0.0.7070                                                           AvalonEdit is the WPF-based text editor used in SharpDevelop 4.0...<br />
AvalonEdit.Sample                                                    4.0.0.7070                                                           Sample code for AvalonEdit the WPF-based text editor used in Sha...<br />
Catel.Windows                                                        0.9.2                                                                Catel.Windows library which includes the MVVM Framework for WPF ...<br />
Catel.Windows                                                        1.0.0                                                                Catel.Windows library which includes the MVVM Framework for WPF ...<br />
EF4Templates                                                         1.1.0.1                                                              EF4 Templates uses T4toolbox to generate Repositories, Unit of w...<br />
MvvmLight                                                            3.0.0.29166                                                          The MVVM Light Toolkit is a set of components helping people to ...<br />
MVVMT4                                                               1.0.0.0                                                              T4 Templates for generating view models, and views for WPF, Silv...<br />
netfx-System.Windows.Input.DelegateCommand                           1.0.0.0                                                              An implementation of WPF ICommand that allows passing delegates/...<br />
Observal                                                             1.0.0.0                                                              Observal is a library that helps you to manage complex, hierarch...<br />
Prism                                                                4.0.0.0                                                              Prism helps you more easily design and build rich, flexible, and...<br />
reactiveui                                                           2.0.0.2                                                              An MVVM library for WPF and Silverlight that is deeply integrate...<br />
reactiveui-xaml                                                      2.0.0.2                                                              WPF and Silverlight specific extensions to ReactiveUI, formerly ...<br />
reactivexaml                                                         1.4.0.0                                                              A MVVM library for WPF and Silverlight that is deeply integrated...<br />
reactivexaml                                                         1.4.1.0                                                              A MVVM library for WPF and Silverlight that is deeply integrated...<br />
SimpleMvvmToolkit.WPF                                                1.1.0.1                                                              Helper classes, Visual Studio templates, code snippets and sampl...<br />
SimpleMvvmToolkit.WPF                                                1.1.0.2                                                              Helper classes, Visual Studio templates, code snippets and sampl...<br />
SimpleMvvmToolkit.WPF                                                1.1.5.0                                                              Helper classes, Visual Studio templates, code snippets and sampl...<br />
</pre>

<p>I then did the same thing for Silverlight:</p>

<pre class="brush: plain;">
PM&gt; get-package -remote -filter silverlight<br />
<br />
Id                                                                   Version                                                              Description                                                    <br />
--                                                                   -------                                                              -----------                                                    <br />
BingMapAppSDK                                                        1.0.1011.1716                                                        With the Bing Map App SDK, you can now create your own map apps ...<br />
Catel.Silverlight                                                    1.0.0                                                                Silverlight version of Catel, including all controls and the MVV...<br />
EF4Templates                                                         1.1.0.1                                                              EF4 Templates uses T4toolbox to generate Repositories, Unit of w...<br />
entile-client                                                        0.1.0                                                                The Entile Notification Framework helps you when doing Live Tile...<br />
FlickrNet.Silverlight                                                3.1.4000                                                             The Flickr.Net API Library is a .Net Library for accessing the F...<br />
FluentAssertions                                                     1.3.0.1                                                              A very extensive set of extension methods for .NET 3.5, 4.0 and ...<br />
FluentValidation                                                     1.3.0.0                                                              A validation library for .NET, Silverlight and WP7 that uses a f...<br />
FluentValidation                                                     2.0.0.0                                                              A validation library for .NET, Silverlight and WP7 that uses a f...<br />
jLight                                                               0.1                                                                  Interop between Silverlight and the javascript based on jQuery. ...<br />
Moq                                                                  4.0.10827                                                            The simplest mocking library for .NET 3.5/4.0 and Silverlight wi...<br />
MvvmLight                                                            3.0.0.29166                                                          The MVVM Light Toolkit is a set of components helping people to ...<br />
MVVMT4                                                               1.0.0.0                                                              T4 Templates for generating view models, and views for WPF, Silv...<br />
Prism                                                                4.0.0.0                                                              Prism helps you more easily design and build rich, flexible, and...<br />
protobuf-net                                                         1.0.0.280                                                            protocol buffers is the name of the binary serialization format ...<br />
qdfeed                                                               1.0.2                                                                A lightweight .NET library designed to give developers an agnost...<br />
ReactiveOAuth                                                        0.2.0.0                                                              Reactive Extensions base OAuth library for .NET Framework 4 Clie...<br />
reactiveui                                                           2.0.0.2                                                              An MVVM library for WPF and Silverlight that is deeply integrate...<br />
reactiveui-xaml                                                      2.0.0.2                                                              WPF and Silverlight specific extensions to ReactiveUI, formerly ...<br />
reactivexaml                                                         1.4.0.0                                                              A MVVM library for WPF and Silverlight that is deeply integrated...<br />
reactivexaml                                                         1.4.1.0                                                              A MVVM library for WPF and Silverlight that is deeply integrated...<br />
SilverlightToolkit-All                                               4.2010.4                                                             The complete Microsoft Silverlight Toolkit.  Details at http://s...<br />
SilverlightToolkit-Core                                              4.2010.4                                                             The core components Microsoft Silverlight Toolkit.  Details at h...<br />
SilverlightToolkit-Data                                              4.2010.4                                                             Data components of the Microsoft Silverlight Toolkit.  Details a...<br />
SilverlightToolkit-DataViz                                           4.2010.4                                                             Data visualization components of the Microsoft Silverlight Toolk...<br />
SilverlightToolkit-Input                                             4.2010.4                                                             Input components of the Microsoft Silverlight Toolkit.  Details ...<br />
SilverlightToolkit-Layout                                            4.2010.4                                                             Layout components of the Microsoft Silverlight Toolkit.  Details...<br />
SilverlightToolkit-Theming                                           4.2010.4                                                             Theming components of the Microsoft Silverlight Toolkit.  Detail...<br />
SilverlightToolkitWP                                                 4.2010.11                                                            The Microsoft Silverlight for Windows Phone Toolkit.  Details at...<br />
SimpleMvvmToolkit.Silverlight                                        1.1.0.1                                                              Helper classes, Visual Studio templates, code snippets and sampl...<br />
SimpleMvvmToolkit.Silverlight                                        1.1.0.2                                                              Helper classes, Visual Studio templates, code snippets and sampl...<br />
SimpleMvvmToolkit.Silverlight                                        1.1.5.0                                                              Helper classes, Visual Studio templates, code snippets and sampl...<br />
StatLight                                                            1.2.3919                                                             StatLight: Tool for executing Silverlight test xap packages loca...<br />
StatLight                                                            1.3.3981                                                             StatLight: Tool for executing Silverlight test xap packages loca...<br />
</pre>

<p>There's a fair amount of stuff available for Silverlight as
well. Very cool, indeed.</p>

<h3>Step 3: Install a Package</h3>

<p>There are a few WPF and Silverlight packages of interest there.
Prism, ReactiveUI, Rx Extensions, the Silverlight Toolkit,
SimpleMvvmToolkit, Windows 7 API Code Pack, and more. I'm going to
install Prism, since it's interesting and has some dependencies
that will need to be resolved.</p>

<p><strong>First, if you haven't already, create a new WPF Windows
app. Most NuGet packages need a project to install
into.</strong></p>

<p>Then, at the command prompt, type "install-package prism"</p>

<pre class="brush: plain;">
PM&gt; install-package prism<br />
'CommonServiceLocator (≥ 1.0)' not installed. Attempting to retrieve dependency from source...<br />
Done<br />
Successfully installed 'CommonServiceLocator 1.0'<br />
You are downloading Prism from Microsoft patterns &amp; practices, the license agreement to which is available at http://compositewpf.codeplex.com/license. Check the package for additional dependencies, which may come with their own license agreement(s). Your use of the package and dependencies constitutes your acceptance of their license agreements. If you do not accept the license agreement(s), then delete the relevant components from your device.<br />
Successfully installed 'Prism 4.0.0.0'<br />
Successfully added 'CommonServiceLocator 1.0' to WpfApplication2<br />
Successfully added 'Prism 4.0.0.0' to WpfApplication2
</pre>

<p>The process took maybe 4 seconds at most (NuGet is really fast)
and updated the references in my project, automatically including
the correct libraries and, as you saw, installing any required
dependencies. Due to the nature of NuGet packages at the moment,
you typically don't get any templates. I hope to see that change in
the future.</p>

<p><a
href="http://10rem.net/media/74024/Windows-Live-Writer_NuGet-for-WPF-and-Silverlight-Developers_E449_image_8.png"
 target="_blank"><img src="http://10rem.net/media/74029/Windows-Live-Writer_NuGet-for-WPF-and-Silverlight-Developers_E449_image_thumb_3.png" width="391" height="451" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></a></p>

<h3>Step 4: Profit</h3>

<p><strong>If you're a tools or toolkit author, put your stuff in
NuGet today.</strong> This is a great package management system
(whether you use the command line or dialog approach) for Visual
Studio. It saves you from having to deal with all the usual hunting
and manual dependency referencing in your projects.</p>

<p>There's a lot of talk inside Microsoft about getting different
projects and packages out on NuGet. Expect to see more soon.</p>

<p>If you're a developer using NuGet, you'll find it often quicker
than using even the new add reference dialog. Definitely go try it
out.</p>
]]></description></item><item><title>Enhancing the WPF Screen Capture Program with Window Borders</title><author>Pete Brown	</author><link>http://10rem.net/blog/2011/02/09/enhancing-the-wpf-screen-capture-program-with-window-borders</link><pubDate>Wed, 09 Feb 2011 20:52:42 GMT</pubDate><guid>http://10rem.net/blog/2011/02/09/enhancing-the-wpf-screen-capture-program-with-window-borders</guid><description><![CDATA[ 
<p>In my <a
href="http://10rem.net/blog/2011/02/08/capturing-screen-images-in-wpf-using-gdi-win32-and-a-little-wpf-interop-help"
 target="_blank">previous post on creating a simple WPF Screen
Capture program</a>, I showed the basics of using the Win32 API and
some WPF to take screen shots of other applications, regions on the
screen, or the full screen. In this post, we'll enhance that sample
to add a visible indicator of what window is being captured.</p>

<p>This example uses the full-screen almost-invisible WPF Window we
created in the previous example. However, I've refactored the code
and made a discrete window type. To the Window's xaml, I added the
transparency properties as well as a red selection region.</p>

<pre class="brush: xml;">
&lt;Window x:Class="PeteBrown.ScreenCapture.CaptureWindow"<br />
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"<br />
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"<br />
        Height="300" Width="300"<br />
        WindowStyle="None"<br />
        ShowInTaskbar="False"<br />
        AllowsTransparency="True"<br />
        Topmost="True"&gt;<br />
    &lt;Grid&gt;<br />
        &lt;Rectangle x:Name="WindowHighlight"<br />
                   Visibility="Collapsed"<br />
                   Stroke="Red"<br />
                   StrokeThickness="3" /&gt;<br />
    &lt;/Grid&gt;<br />
&lt;/Window&gt;<br />
</pre>

<p>Those window style and transparency settings were set in code in
the previous version.</p>

<p>The capture window itself is very similar to what we had in the
previous example. However, I added two events (discussed below),
and the code to handle the highlight. Here's the highlight
code:</p>

<pre class="brush: csharp;">
private IntPtr _hoveredHWnd = IntPtr.Zero;<br />
void CaptureWindow_MouseMove(object sender, MouseEventArgs e)<br />
{<br />
    Point current = e.GetPosition(this);<br />
    Point screenCoords = PointToScreen(current);<br />
<br />
    // this hide and show causes flicker, but using this<br />
    // approach, there's not much you can do about that.<br />
    // Caching the window rect doesn't help in the case of overlapping<br />
    // windows. One thing you could do is run through and cache *all*<br />
    // window rects. You could do some interesting things with that<br />
    // but unless you restrict yourself to top-level windows, you'll<br />
    // have a lot of rects to deal with<br />
    Hide();<br />
<br />
    IntPtr hWnd = User32.WindowFromPoint(new Win32Point((int)screenCoords.X, (int)screenCoords.Y));<br />
<br />
    Show();<br />
<br />
    if (hWnd != IntPtr.Zero)<br />
    {<br />
        // don't bother changing things if this is the same<br />
        // window we've been over<br />
        if (hWnd != _hoveredHWnd)<br />
        {<br />
            // get the dimensions of the window we're hovered over<br />
            Win32Rect rect = new Win32Rect();<br />
            User32.GetWindowRect(hWnd, out rect);<br />
<br />
            Point topLeft = PointFromScreen(new Point(rect.Left, rect.Top));<br />
                  <br />
<br />
            WindowHighlight.Width = rect.Width;<br />
            WindowHighlight.Height = rect.Height;<br />
            WindowHighlight.Margin = new Thickness(<br />
                topLeft.X,<br />
                topLeft.Y,<br />
                Width - rect.Width - topLeft.X,<br />
                Height - rect.Height - topLeft.Y);<br />
<br />
            WindowHighlight.Visibility = Visibility.Visible;<br />
        }<br />
    }<br />
}
</pre>

<p>This code hides the window, calls the API call to get the hWnd
under the mouse cursor, then, if the window isn't already selected,
sizes and moves the red rectangle to highlight the bounds of that
hWnd. To be clear, there is a fair amount of flicker when you keep
the mouse relatively steady over the same window. I need to do
something about that.</p>

<p>As I mentioned, the selection code itself is very similar to
what we had before, but with the addition of WindowSelected and
Canceled events.</p>

<pre class="brush: csharp;">
private Point _mouseDown;<br />
void CaptureWindow_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)<br />
{<br />
    _mouseDown = e.GetPosition(this);<br />
}<br />
<br />
void CaptureWindow_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)<br />
{<br />
    Point current = e.GetPosition(this);<br />
<br />
    if (Math.Abs(_mouseDown.X - current.X) &lt; 10.0 &amp;&amp;<br />
        Math.Abs(_mouseDown.Y - current.Y) &lt; 10.0)<br />
    {<br />
        // this is the window they want<br />
<br />
        Point screenCoords = PointToScreen(current);<br />
        Hide();<br />
<br />
        IntPtr hWnd = User32.WindowFromPoint(new Win32Point((int)screenCoords.X, (int)screenCoords.Y));<br />
        User32.SetForegroundWindow(hWnd);<br />
<br />
        SelectedHWnd = hWnd;<br />
<br />
        OnWindowSelected();<br />
    }<br />
}<br />
<br />
protected void OnWindowSelected()<br />
{<br />
    if (WindowSelected != null)<br />
        WindowSelected(this, EventArgs.Empty);<br />
}
</pre>

<p>The attached source code includes the cancel and event wire-up
code as well.</p>

<p>I then modified the calling code in the main window to use the
new window and sink the new events. Originally, I had this as a
modal window with a regular DialogResult. However, due to the need
to actually hide the window before making the Win32 API call
(setting visibility or opacity wouldn't work), and re-show it, that
doesn't work. So, I went from a modal approach to an event-driven
approach.</p>

<p>In this partial screen shot (taken with normal print screen) you
can see the red selection highlight around Visual Studio.</p>

<p><a
href="http://10rem.net/media/73962/Windows-Live-Writer_90b50775603a_ADA7_image_6.png"
 target="_blank"><img src="http://10rem.net/media/73967/Windows-Live-Writer_90b50775603a_ADA7_image_thumb_2.png" width="520" height="336" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></a></p>

<p>Note that as was the case in the previous version of the code,
the calls here do not restrict you to the main window hWnd. I'll
want to modify the code to do that for this specific scenario
(where we're expanding the size to include the border and shadow),
but still retain an "any hWnd" mode, as that's pretty useful as
well.</p>

<p><a
href="http://10rem.net/media/73972/Windows-Live-Writer_90b50775603a_ADA7_image_8.png"
 target="_blank"><img src="http://10rem.net/media/73977/Windows-Live-Writer_90b50775603a_ADA7_image_thumb_3.png" width="519" height="226" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></a></p>

<p>The Clipboard functionality is still disabled. I'll address that
in an upcoming post. I promise! :)</p>
]]></description></item><item><title>Capturing Screen Images in WPF using GDI, Win32 and a little WPF Interop Help</title><author>Pete Brown	</author><link>http://10rem.net/blog/2011/02/08/capturing-screen-images-in-wpf-using-gdi-win32-and-a-little-wpf-interop-help</link><pubDate>Tue, 08 Feb 2011 05:14:41 GMT</pubDate><guid>http://10rem.net/blog/2011/02/08/capturing-screen-images-in-wpf-using-gdi-win32-and-a-little-wpf-interop-help</guid><description><![CDATA[ 
<p>I keep a backlog of project/blog/video ideas on my machine here.
One that I've had sitting there for a bit, and something that
really interests me, is how to create a simple screen capture
(still image) program using WPF.</p>

<p>I use a ton of screen shots in my applications. Before I joined
Microsoft (when I was an MVP), I used Snag-it for just about
everything. On this new machine, I haven't installed any screen
capture apps at all. However, tools like <a
href="http://blois.us/Rooler/" target="_blank">Rooler by Pete
Blois</a> and <a href="http://cropper.codeplex.com/"
target="_blank">Cropper</a> up on CodePlex would be good
candidates.</p>

<p>Of course, I want to build one myself anyway to learn how it's
done. So, let's have at it.</p>

<h3>Capturing a Region</h3>

<p>The first task I decided to tackle is that of snap-shotting a
region of the screen. Here's an example of a region which includes
part of Visual Studio.</p>

<p><a
href="http://10rem.net/media/73850/Windows-Live-Writer_Capturing-Screen-Images-in-WPF-using-GDI_EE63_image_10.png"
 target="_blank"><img src="http://10rem.net/media/73855/Windows-Live-Writer_Capturing-Screen-Images-in-WPF-using-GDI_EE63_image_thumb_4.png" width="500" height="357" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></a></p>

<p>I wanted to keep it simple, so I didn't implement rubber-band
selection or anything. A real app, of course, would need that.
Instead, I decided just to hard-code the rectangle and test out the
rest of the code from there.</p>

<p>There are three buttons, an Image and a Border in the Xaml. The
one button we're concerned with for this example is the
CaptureRegion button. It and the image are defined as follows:</p>

<pre class="brush: xml;">
&lt;Button Content="Region"<br />
        Height="23"<br />
        HorizontalAlignment="Left"<br />
        Margin="10,68,0,0"<br />
        x:Name="CaptureRegion"<br />
        VerticalAlignment="Top"<br />
        Width="100"<br />
        Click="CaptureRegionButton_Click" /&gt;<br />
<br />
&lt;Border Background="LightGray"<br />
        BorderBrush="Black"<br />
        Grid.Column="1"<br />
        Margin="10"&gt;<br />
    &lt;Image x:Name="CapturedImage"<br />
            RenderOptions.BitmapScalingMode="Fant"<br />
            Stretch="Uniform" /&gt;<br />
&lt;/Border&gt;<br />
</pre>

<p>Note the RenderOptions.BitmapScalingMode setting on the Image.
When displaying we're typically resizing an image by far more than
50%, so you want a more aggressive smoothing algorithm. See more on
my posts about <a
href="http://10rem.net/blog/2010/05/01/crappy-image-resizing-in-wpf-try-renderoptionsbitmapscalingmode"
 target="_blank">image resizing in WPF 4 here</a> and <a
href="http://10rem.net/blog/2010/05/16/more-on-image-resizing-in-net-4-vs-net-35sp1-bilinear-vs-fant"
 target="_blank">here</a>.</p>

<p>For this example, I implemented the call in code-behind.</p>

<pre class="brush: csharp;">
private void CaptureRegionButton_Click(object sender, RoutedEventArgs e)<br />
{<br />
    CapturedImage.Source = ScreenCapture.CaptureRegion(100, 100, 500, 500, true);<br />
}
</pre>

<p>You can see that we're capturing a region starting at 100x100
with a size of 500,500. The last parameter says to copy to the
clipboard -- more on that later.</p>

<p>Now for the important part. Capturing the region. This involves
grabbing the desktop window, since a region may overlap windows,
and rendering a portion of that to a bitmap. While much of it is
Win32 API gunk (I'll leave out the Win32 API declarations; you can
see them in the source code attached to this post), there's one
really nice helper from WPF: the Imaging interop class.</p>

<pre class="brush: csharp; highlight: [28,29,30];">
// capture a region of a the screen, defined by the hWnd<br />
public static BitmapSource CaptureRegion(<br />
    IntPtr hWnd, int x, int y, int width, int height, bool addToClipboard)<br />
{<br />
    IntPtr sourceDC = IntPtr.Zero;<br />
    IntPtr targetDC = IntPtr.Zero;<br />
    IntPtr compatibleBitmapHandle = IntPtr.Zero;<br />
    BitmapSource bitmap = null;<br />
<br />
    try<br />
    {<br />
        // gets the main desktop and all open windows<br />
        sourceDC = User32.GetDC(User32.GetDesktopWindow());<br />
        //sourceDC = User32.GetDC(hWnd);<br />
        targetDC = Gdi32.CreateCompatibleDC(sourceDC);<br />
<br />
        // create a bitmap compatible with our target DC<br />
        compatibleBitmapHandle = Gdi32.CreateCompatibleBitmap(sourceDC, width, height);<br />
<br />
        // gets the bitmap into the target device context<br />
        Gdi32.SelectObject(targetDC, compatibleBitmapHandle);<br />
<br />
        // copy from source to destination<br />
        Gdi32.BitBlt(targetDC, 0, 0, width, height, sourceDC, x, y, Gdi32.SRCCOPY);<br />
<br />
        // Here's the WPF glue to make it all work. It converts from an<br />
        // hBitmap to a BitmapSource. Love the WPF interop functions<br />
        bitmap = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(<br />
            compatibleBitmapHandle, IntPtr.Zero, Int32Rect.Empty,<br />
            BitmapSizeOptions.FromEmptyOptions());<br />
             <br />
<br />
<br />
    }<br />
    catch (Exception ex)<br />
    {<br />
        throw new ScreenCaptureException(string.Format("Error capturing region {0},{1},{2},{3}", x, y, width, height), ex);<br />
    }<br />
    finally<br />
    {<br />
        Gdi32.DeleteObject(compatibleBitmapHandle);<br />
<br />
        User32.ReleaseDC(IntPtr.Zero, sourceDC);<br />
        User32.ReleaseDC(IntPtr.Zero, targetDC);<br />
    }<br />
<br />
    return bitmap;<br />
}
</pre>

<p>We use the Imaging interop class to create a WPF-compatible
BitmapSource from a Windows hBitmap. Note that I'm not doing
anything with the Clipboard parameter in this code. The clipboard
portion is not yet working, but is included in the source code.</p>

<p>That's all there is to capturing a region. It's super simple
once you realize there's this great helper functionality included
in the WPF interop namespace.</p>

<p>Next, we'll expand this to capture the entire screen.</p>

<h3>Capturing the Entire Screen</h3>

<p>The second thing I decided to do is implement a simple
Print-Screen function which snapshots the entire virtual screen
space. Here's an example of a screen shot from this machine:</p>

<p><a
href="http://10rem.net/media/73860/Windows-Live-Writer_Capturing-Screen-Images-in-WPF-using-GDI_EE63_image_4.png"
 target="_blank"><img src="http://10rem.net/media/73865/Windows-Live-Writer_Capturing-Screen-Images-in-WPF-using-GDI_EE63_image_thumb_1.png" width="500" height="357" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></a></p>

<p>You can see from the above screenshot that I have two displays
stacked on each other. Windows does a good job of providing both
images, with appropriate transparency where no display occupies
that space.</p>

<p>The nice part about this is it uses the existing CaptureRegion
function to do all the heavy lifting:</p>

<pre class="brush: csharp;">
public static BitmapSource CaptureFullScreen(bool addToClipboard)<br />
{<br />
    return CaptureRegion(<br />
        User32.GetDesktopWindow(),<br />
        (int)SystemParameters.VirtualScreenLeft,<br />
        (int)SystemParameters.VirtualScreenTop,<br />
        (int)SystemParameters.VirtualScreenWidth,<br />
        (int)SystemParameters.VirtualScreenHeight,<br />
        addToClipboard);<br />
}
</pre>

<p>The key thing to note in this chunk of code is the
SystemParameters object which provides the size of the full
screen.</p>

<p>The next task is to capture a single window. This is where
things start getting hairy.</p>

<h3>Capturing a Single Window</h3>

<p>I'm not a fan of Alt-PrtScn to capture a single window. When you
do that, you lose the nice shadow effect from Windows 7 and Vista,
and get an ugly chopped image with dark corners (since it leave the
shadow there, but doesn't mask the rounded corners). Here's an
example:</p>

<p><a
href="http://10rem.net/media/73870/Windows-Live-Writer_Capturing-Screen-Images-in-WPF-using-GDI_EE63_image_14.png"
 target="_blank"><img src="http://10rem.net/media/73875/Windows-Live-Writer_Capturing-Screen-Images-in-WPF-using-GDI_EE63_image_thumb_6.png" width="500" height="299" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></a></p>

<p>Not only do we have the corner problem, but due to aero glass,
background content shows through. On a full desktop, that content
adds context, but in a screenshot, it just looks messy. Screenshots
like that just look unprofessional. I did my best to make sure they
don't show up in my books or on my blog.</p>

<p>The attached source code has the start of a blanking approach: I
stick a blank window behind the target window before doing the
screen shot. It's not stable and suffers from a race condition, so
I'll not include that code in this blog post. However, I will show
you how to capture the full window including the shadow.</p>

<p>Warning: Lark's Vomit!</p>

<p>(that was a Big Red Label. Look it up &lt;g&gt;)</p>

<p>Ok, seriously. This code has magic numbers. I hate magic
numbers. <strong>There is likely a nice systemic way to retrieve
the exact dimensions I need, including shadows and whatnot.
However, it eludes me at the moment</strong>. Use the code if you
want, but realize you're inheriting disease. Don't blame me if you
implement a mission critical print-screen hospital patient
monitoring system and someone gets +/- 5% dosage or something
;)</p>

<p>First, the main window capture function (with blanking window
code removed):</p>

<pre class="brush: csharp;">
public static BitmapSource CaptureWindow(IntPtr hWnd, bool recolorBackground, Color substituteBackgroundColor, bool addToClipboard)<br />
{<br />
    Int32Rect rect = GetWindowActualRect(hWnd);<br />
<br />
    Window blankingWindow = null;<br />
<br />
    if (recolorBackground)<br />
    {<br />
        // ... blanking window gunk ...<br />
    }<br />
<br />
    // bring the to-be-captured window to capture to the foreground<br />
    // there's a race condition here where the blanking window<br />
    // sometimes comes to the top. Hate those. There is surely<br />
    // a non-WPF native solution to the blanking window which likely<br />
    // involves drawing directly on the desktop or the target window<br />
         <br />
    User32.SetForegroundWindow(hWnd);<br />
<br />
    BitmapSource captured = CaptureRegion(<br />
        hWnd,<br />
        rect.X,<br />
        rect.Y,<br />
        rect.Width,<br />
        rect.Height,<br />
        true);<br />
<br />
    if (blankingWindow != null)<br />
        blankingWindow.Close();<br />
<br />
    return captured;<br />
}
</pre>

<p>One function in there deserves calling-out: GetWindowActualRect.
This is where the majority of fudging happens</p>

<pre class="brush: csharp;">
// this accounts for the border and shadow. Serious fudgery here.<br />
private static Int32Rect GetWindowActualRect(IntPtr hWnd)<br />
{<br />
    Win32Rect windowRect = new Win32Rect();<br />
    Win32Rect clientRect = new Win32Rect();<br />
<br />
    User32.GetWindowRect(hWnd, out windowRect);<br />
    User32.GetClientRect(hWnd, out clientRect);<br />
<br />
    int sideBorder = (windowRect.Width - clientRect.Width)/2 + 1;<br />
<br />
    // sooo, yeah.<br />
    const int hackToAccountForShadow = 4;<br />
<br />
    Win32Point topLeftPoint = new Win32Point(windowRect.Left - sideBorder, windowRect.Top - sideBorder);<br />
<br />
    //User32.ClientToScreen(hWnd, ref topLeftPoint);<br />
<br />
    Int32Rect actualRect = new Int32Rect(<br />
        topLeftPoint.X,<br />
        topLeftPoint.Y,<br />
        windowRect.Width + sideBorder * 2 + hackToAccountForShadow,<br />
        windowRect.Height + sideBorder * 2 + hackToAccountForShadow);<br />
<br />
    return actualRect;<br />
}
</pre>

<p>There are a couple problems related to the magic numbers:</p>

<ol>
<li>You can incorrect results with maximized windows. I can check
for this and handle it in code.</li>

<li>Some windows just don't cooperate with this. Again, Windows
Live Writer is one that throws me. Most of the other Windows all
behave nicely, but the WLW window ends up shifted over a few
pixels.</li>

<li>This hasn't been tested on Aero Basic</li>

<li>When you click on child hWnds (like the web page inside the
browser, or the editor inside Visual Studio) the fudge numbers no
longer make sense.</li>
</ol>

<p>Other than that, it does a decent job of capturing the window
itself, including its aero borders and shadows.</p>

<p>Once we have the actual bounds of the window (including
shadows), the code simply calls the same CaptureRegion code from
before. Here's an example of capturing the Visual Studio
window.</p>

<p><a
href="http://10rem.net/media/73880/Windows-Live-Writer_Capturing-Screen-Images-in-WPF-using-GDI_EE63_image_2.png"
 target="_blank"><img src="http://10rem.net/media/73885/Windows-Live-Writer_Capturing-Screen-Images-in-WPF-using-GDI_EE63_image_thumb.png" width="500" height="356" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></a></p>

<p>Without the white blanking window in the background, it looks
ugly, I know. That <strong>is</strong> a solvable problem and
<strong>will</strong> be dealt with.</p>

<p>But wait, how did I go about picking that particular window for
capture? Ahh, that's the next part :)</p>

<h3>Picking a Window with the Mouse</h3>

<p>I didn't want this to be a completely academic exercise, so I
figured I had better put in some realistic functionality. That
comes in the form of using the mouse to select the window you want
to capture.</p>

<pre class="brush: csharp;">
private void CaptureWindowWithBackgroundButton_Click(object sender, RoutedEventArgs e)<br />
{<br />
    PickWindowWithMouse();<br />
}<br />
<br />
private void PickWindowWithMouse()<br />
{<br />
    Window captureWindow = new Window();<br />
<br />
    captureWindow.WindowStyle = WindowStyle.None;<br />
    captureWindow.Title = string.Empty;<br />
    captureWindow.ShowInTaskbar = false;<br />
    captureWindow.AllowsTransparency = true;<br />
    captureWindow.Background = new SolidColorBrush(Color.FromArgb(0x01, 0x00, 0x00, 0x00));<br />
    captureWindow.Topmost = true;<br />
<br />
    captureWindow.Left = SystemParameters.VirtualScreenLeft;<br />
    captureWindow.Top = SystemParameters.VirtualScreenTop;<br />
    captureWindow.Width = SystemParameters.VirtualScreenWidth;<br />
    captureWindow.Height = SystemParameters.VirtualScreenHeight;<br />
<br />
    Point mouseDown = new Point();<br />
<br />
    captureWindow.KeyUp += (s, e) =&gt;<br />
        {<br />
            if (e.Key == Key.Escape)<br />
            {<br />
                // cancel the capture<br />
                captureWindow.Close();<br />
                this.Show();<br />
            }<br />
        };<br />
<br />
    captureWindow.MouseDown += (s, e) =&gt;<br />
        {<br />
            mouseDown = e.GetPosition(captureWindow);<br />
        };<br />
<br />
    captureWindow.MouseUp += (s, e) =&gt;<br />
        {<br />
            Point current = e.GetPosition(captureWindow);<br />
<br />
            if (Math.Abs(mouseDown.X - current.X) &lt; 10.0 &amp;&amp;<br />
                Math.Abs(mouseDown.Y - current.Y) &lt; 10.0)<br />
            {<br />
                // this is the window they want<br />
<br />
                Point screenCoords = captureWindow.PointToScreen(current);<br />
                captureWindow.Close();<br />
<br />
                IntPtr hWnd = User32.WindowFromPoint(new Win32Point((int)screenCoords.X, (int)screenCoords.Y));<br />
                User32.SetForegroundWindow(hWnd);<br />
<br />
                //CapturedImage.Source = ScreenCapture.CaptureWindow(hWnd, true, Colors.White, true);<br />
                CapturedImage.Source = ScreenCapture.CaptureWindow(hWnd, false, Colors.Transparent, true);<br />
<br />
                // show our app window again, and bring it to the foreground<br />
                WindowInteropHelper helper = new WindowInteropHelper(this);<br />
                this.Show();<br />
                User32.SetForegroundWindow(helper.Handle);<br />
                     <br />
            }<br />
        };<br />
<br />
    this.Hide();<br />
    captureWindow.Show();<br />
<br />
}<br />
<br />
</pre>

<p>To handle this, I create a full-screen WPF window and use it to
capture the click. Windows don't have a click event, so I check to
see if the MouseUp event is raised within 10 pixels of the
MouseDown event. The window covers the entire screen, so I don't
bother with capturing the mouse.</p>

<p>I then use the Win32 API to map that click to a hWnd in Windows.
That hWnd doesn't always resolve to a top-level application. For
example, IE8: if I click in the web page, the only part that is
captured is the rendered web page (the portion viewable on-screen).
I have to click in the title bar or tool bar to get the full IE
window.</p>

<p>So, in a nutshell:</p>

<ul>
<li>Hide this app window</li>

<li>Show the capture window</li>

<li>Capture the mouse click</li>

<li>Hide the capture window</li>

<li>Map the mouse click to an app</li>

<li>Bring that app to the front (so whole window is visible)</li>

<li>Capture the image</li>

<li>Show my app's window again</li>

<li>Bring my app's window to the front</li>
</ul>

<p>The user can press escape at any time to close the capture
window.</p>

<p>The full-screen WPF window is not the only available option.
However, I'll want to have that available for rubber band selection
and other possible enhancements in the future, so using it here
imposes no hard tax.</p>

<h3>Features that are Not Quite Working</h3>

<p>As mentioned, the code has some additional stuff not shown here.
It's not shown because it's not working that well. The first is the
ability to add a blanking window behind the window being captured.
This is good for getting nice clean screenshots, typically on a
white background. When taking normal screen shots using
Print-Screen, I manually do this by hovering the window over
notepad when using print screen. Crude, but works. I want a better
solution.</p>

<p>The second bit is the clipboard. I wrestled with the clipboard
tonight but couldn't get it to put a good default format in that
was recognized by Windows Live Writer. As written, it will paste
into MS Word and even MS Paint. WLW, on the other hand, doesn't
recognize what's there. Obviously something's amiss.</p>

<p>So, expect a follow-up should I come up with decent solutions
for these issues. Feel free to tinker with the code on your own as
well.</p>
]]></description></item><item><title>Windows File Dialog Custom Places in WPF 4</title><author>Pete Brown	</author><link>http://10rem.net/blog/2011/01/29/windows-file-dialog-custom-places-in-wpf-4</link><pubDate>Sat, 29 Jan 2011 21:01:02 GMT</pubDate><guid>http://10rem.net/blog/2011/01/29/windows-file-dialog-custom-places-in-wpf-4</guid><description><![CDATA[ 
<p>Starting with Windows Vista, the open and save file dialog boxes
have a panel on the left side containing favorite links. These
links are known as "Custom Places". Previously, the built-in
Windows dialogs were available only if you used the Windows Forms
versions. However, starting with WPF 4 on Windows 7 and Windows
Vista support of native file dialogs with custom places via the
FileDialogCustomPlace and FileDialogCustomPlaces classes can be
found in the Microsoft.Win32 namespace right in the
PresentationFramework dll.</p>

<h3>Using Standard Custom Places</h3>

<p>The framework includes a number of built-in custom places,
representing the usual system and user locations on the machine,
plus the local and roaming profile locations. To use them, simply
use the static instances provided by the FileDialogCustomPlaces
class.</p>

<pre class="brush: csharp;">
private void SaveButton_Click(object sender, RoutedEventArgs e)<br />
{<br />
    SaveFileDialog dialog = new SaveFileDialog();<br />
<br />
    dialog.CustomPlaces.Add(FileDialogCustomPlaces.LocalApplicationData);<br />
    dialog.CustomPlaces.Add(FileDialogCustomPlaces.Templates);<br />
<br />
    dialog.ShowDialog();<br />
}
</pre>

<p>When displayed, the dialog will have two custom places shown at
the top left (refer to screen shot in the next section): the local
application data folder and the templates folder.</p>

<p>The standard places supplied are (from <a
href="http://msdn.microsoft.com/en-us/library/microsoft.win32.filedialogcustomplaces.aspx"
 target="_blank">MSDN</a>) :</p>

<table border="1" cellspacing="0" cellpadding="2"
style="width: 550px;">
<tbody>
<tr>
<td width="170" valign="top"><strong>Name</strong></td>
<td width="380" valign="top"><strong>Description</strong></td>
</tr>

<tr>
<td width="170" valign="top">Contacts</td>
<td width="380" valign="top">Contacts folder for the current
user.</td>
</tr>

<tr>
<td width="170" valign="top">Cookies</td>
<td width="380" valign="top">Internet cookies folder for the
current user.</td>
</tr>

<tr>
<td width="170" valign="top">Desktop</td>
<td width="380" valign="top">Folder for storing files on the
desktop for the current user.</td>
</tr>

<tr>
<td width="170" valign="top">Documents</td>
<td width="380" valign="top">Documents folder for the current
user.</td>
</tr>

<tr>
<td width="170" valign="top">Favorites</td>
<td width="380" valign="top">Favorites folder for the current
user.</td>
</tr>

<tr>
<td width="170" valign="top">LocalApplicationData</td>
<td width="380" valign="top">Folder for application-specific data
that is used by the current, non-roaming user.</td>
</tr>

<tr>
<td width="170" valign="top">Music</td>
<td width="380" valign="top">Music folder for the current
user.</td>
</tr>

<tr>
<td width="170" valign="top">Pictures</td>
<td width="380" valign="top">Pictures folder for the current
user.</td>
</tr>

<tr>
<td width="170" valign="top">ProgramFiles</td>
<td width="380" valign="top">Program Files folder.</td>
</tr>

<tr>
<td width="170" valign="top">ProgramFilesCommon</td>
<td width="380" valign="top">Folder for components that are shared
across applications.</td>
</tr>

<tr>
<td width="170" valign="top">Programs</td>
<td width="380" valign="top">Folder that contains the program
groups for the current user.</td>
</tr>

<tr>
<td width="170" valign="top">RoamingApplicationData</td>
<td width="380" valign="top">Folder for application-specific data
for the current roaming user.</td>
</tr>

<tr>
<td width="170" valign="top">SendTo</td>
<td width="380" valign="top">Folder that contains the Send To menu
items for the current user.</td>
</tr>

<tr>
<td width="170" valign="top">StartMenu</td>
<td width="380" valign="top">Folder that contains the Start menu
items for the current user.</td>
</tr>

<tr>
<td width="170" valign="top">Startup</td>
<td width="380" valign="top">Folder that corresponds to the Startup
program group for the current user.</td>
</tr>

<tr>
<td width="170" valign="top">System</td>
<td width="380" valign="top">System folder.</td>
</tr>

<tr>
<td width="170" valign="top">Templates</td>
<td width="380" valign="top">Folder for document templates for the
current user.</td>
</tr>
</tbody>
</table>

<p>While the standard places will suffice for most applications,
especially since they include the local application data folder,
you may wish to provide additional locations. This is accomplished
via the FileDialogCustomPlace class.</p>

<h3>Adding Your Own Places</h3>

<p>Sometimes the built-in places aren't sufficient for all the
locations you'd like to surface to the user. For example, I have
some software recording/sequencing applications. Many of those
share the same folder for plug-ins, known as VSTs. I may want to
provide the ability for the user to quickly locate that folder in
the open and save file dialogs. This is accomplished by creating an
instance of the FileDialogCustomPlace class.</p>

<pre class="brush: csharp;">
private void SaveButton_Click(object sender, RoutedEventArgs e)<br />
{<br />
    SaveFileDialog dialog = new SaveFileDialog();<br />
<br />
    string appSpecialPath = @"C:\Program Files (x86)\Image-Line\FL Studio 9\Plugins\VST";<br />
<br />
    FileDialogCustomPlace place = new FileDialogCustomPlace(appSpecialPath);<br />
<br />
    dialog.CustomPlaces.Add(place);<br />
    dialog.CustomPlaces.Add(FileDialogCustomPlaces.LocalApplicationData);<br />
    dialog.CustomPlaces.Add(FileDialogCustomPlaces.Templates);<br />
<br />
    dialog.ShowDialog();<br />
<br />
}
</pre>

<p>The FileDialogCustomPlace class constructor takes in either a
string path or a GUID which refers to one of the built-in places.
In this case, I supplied it with the VST plug-in folder. When run,
the dialog looks like this:</p>

<p><img src="http://10rem.net/media/73546/Windows-Live-Writer_Windows-Dialog-Custom-Places-in-WPF-4_D494_image_3.png" width="580" height="362" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></p>

<p>Note that the name of the folder is displayed using normal
Windows mechanisms: you get just the name of the final folder in
the path.</p>

<p>Also note that on Windows XP, the custom places will have no
effect. The feature is gracefully dropped.</p>
]]></description></item><item><title>Puff the Magic POCO Binding and INotifyPropertyChanged in WPF</title><author>Pete Brown	</author><link>http://10rem.net/blog/2010/12/17/puff-the-magic-poco-binding-and-inotifypropertychanged-in-wpf</link><pubDate>Fri, 17 Dec 2010 18:27:28 GMT</pubDate><guid>http://10rem.net/blog/2010/12/17/puff-the-magic-poco-binding-and-inotifypropertychanged-in-wpf</guid><description><![CDATA[ 
<p>Yesterday I wrote a <a
href="http://10rem.net/blog/2010/12/16/strategies-for-improving-inotifypropertychanged-in-wpf-and-silverlight"
 target="_blank">post about different ways of working with
INotifyPropertyChanged</a>. One of my readers (who only went by
"Guest") pointed out that binding "magically" worked in WPF with
POCOs (Plain Old CLR Objects) that didn't bother to implement
INotifyPropertyChanged. I thought for sure he/she was wrong … until
I tried it myself. Magic, I say! Magic!</p>

<p>Then again, as one of the WPF team members pointed out to me,
this is a great example of <a
href="http://en.wikipedia.org/wiki/Clarke's_three_laws"
target="_blank">Clarke's third law</a>. :)</p>

<p>Take this example:</p>

<pre class="brush: xml; highlight: [9,18,19];">
&lt;Window x:Class="WpfApplication1.MainWindow"<br />
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"<br />
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"<br />
        Title="MainWindow" Height="350" Width="525"&gt;<br />
    &lt;Grid&gt;<br />
        &lt;ListBox x:Name="PeopleList"<br />
                 Height="287"<br />
                 HorizontalAlignment="Left"<br />
                 DisplayMemberPath="LastName"<br />
                 Margin="12,12,0,0"<br />
                 VerticalAlignment="Top"<br />
                 Width="138" /&gt;<br />
        &lt;TextBox Height="23"<br />
                 HorizontalAlignment="Left"<br />
                 Margin="265,24,0,0"<br />
                 x:Name="LastNameField"<br />
                 VerticalAlignment="Top"<br />
                 DataContext="{Binding ElementName=PeopleList, Path=SelectedItem}"<br />
                 Text="{Binding LastName}"<br />
                 Width="120" /&gt;<br />
        &lt;TextBlock Height="23"<br />
                   HorizontalAlignment="Left"<br />
                   Margin="178,27,0,0"<br />
                   Text="Last Name"<br />
                   VerticalAlignment="Top" /&gt;<br />
    &lt;/Grid&gt;<br />
&lt;/Window&gt;<br />
</pre>

<p>Here's the Person Class</p>

<pre class="brush: csharp;">
class Person<br />
{<br />
    public string FirstName { get; set; }<br />
    public string LastName { get; set; }<br />
}
</pre>

<p>Here's the Code-behind</p>

<pre class="brush: csharp;">
public partial class MainWindow : Window<br />
{<br />
    private ObservableCollection&lt;Person&gt; _people;<br />
<br />
    public MainWindow()<br />
    {<br />
        InitializeComponent();<br />
<br />
        _people = new ObservableCollection&lt;Person&gt;();<br />
<br />
        _people.Add(new Person() { LastName = "Brown" });<br />
        _people.Add(new Person() { LastName = "Fitz" });<br />
        _people.Add(new Person() { LastName = "Hanselman" });<br />
        _people.Add(new Person() { LastName = "Heuer" });<br />
        _people.Add(new Person() { LastName = "Galloway" });<br />
        _people.Add(new Person() { LastName = "Stagner" });<br />
        _people.Add(new Person() { LastName = "Liberty" });<br />
        _people.Add(new Person() { LastName = "Litwin" });<br />
        _people.Add(new Person() { LastName = "Papa" });<br />
        _people.Add(new Person() { LastName = "Guthrie" });<br />
<br />
        PeopleList.ItemsSource = _people;<br />
    }<br />
}
</pre>

<p>When you run this little application, and modify the value in
the TextBox, the value in the ListBox is updated, seemingly by
magic.</p>

<p><img src="http://10rem.net/media/73042/Windows-Live-Writer_Magic-POCO-Binding-and-INotifyPropertyCh_11172_image_3.png" width="550" height="374" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></p>

<p>There it is. The value in the ListBox updated right when I
tabbed off of the last name field. Magic code? Spirits? Too much
alcohol? What is happening here?</p>

<h3>What's Really Happening</h3>

<p>The Person class has a <a
href="http://msdn.microsoft.com/en-us/library/system.componentmodel.propertydescriptor.aspx"
 target="_blank">PropertyDescriptor</a> for each property. The
PropertyDescriptor has the AddValueChanged method by which a
listener can sign up to get the property change notifications from
that descriptor. That's what the behind-the-scenes binding is doing
- wiring up a value changed event for the property descriptor in
play in the binding.</p>

<p>Note this only works when using binding. If you update the
values from code, the change won't be notified.</p>

<p>What's happening is actually a perfectly valid (if not optimal)
way to handle binding and change notification. What WPF is doing
behind the scenes in this case is something you could explicitly
put in your own code if you wish.</p>

<h3>Implications</h3>

<p><strong>The PropertyDescriptor class is pretty heavy.</strong>
In addition, WPF must request the full set of descriptors for the
class, not just a single descriptor. If you have a class with a
large number of properties, regardless of how many are actually
involved in binding, the CPU and <strong>memory usage associated
with that call can be both significant and measurable</strong>. In
one instance, the memory used to get all the property descriptors
for a large class was around 800K!</p>

<p>But doesn't WPF need that for binding anyway?</p>

<p>No. WPF uses the much <a
href="http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.aspx"
 target="_blank">lighter weight PropertyInfo class</a> when
binding. If you explicitly implement INotifyPropertyChanged, all
WPF needs to do is call the PropertyInfo.GetValue method to get the
latest value. That's quite a bit less work than getting all the
descriptors. <strong>Descriptors end up costing in the order of 4x
the memory of the property info classes</strong>.</p>

<p>Note also that if you have a reference from the POCO back in the
UI (we don't do that, right…right?) you may be subject to <a
href="http://support.microsoft.com/kb/938416" target="_blank">the
memory leak described in KB938416</a>. That only applies to the
PropertyDescriptor-based approach, which in this post, is POCO
only.</p>

<h3>Summary</h3>

<p>Implementing INotifyPropertyChanged can be a fair bit of tedious
development work. However, you'll need to weigh that work against
the runtime footprint (memory and CPU) of your WPF application.
Implementing INPC yourself will save runtime CPU and memory.</p>

<p>Thanks to the WPF team for the detailed information about what's
going on here. I love being able to talk to the people who actually
wrote the code :)</p>

<p>Note that Silverlight does not have the PropertyDescriptor
class, so this doesn't apply there.</p>
]]></description></item><item><title>Strategies for Improving INotifyPropertyChanged in WPF and Silverlight</title><author>Pete Brown	</author><link>http://10rem.net/blog/2010/12/16/strategies-for-improving-inotifypropertychanged-in-wpf-and-silverlight</link><pubDate>Thu, 16 Dec 2010 17:38:00 GMT</pubDate><guid>http://10rem.net/blog/2010/12/16/strategies-for-improving-inotifypropertychanged-in-wpf-and-silverlight</guid><description><![CDATA[ 
<p>The Silverlight and WPF binding system is extremely powerful.
With it, you can bind your UI to your viewmodels (or other backing
objects), bind control values to each other (for example, a slider
controlling an object's scale or rotation) all with little or no
code.</p>

<p>In order for binding to work, it requires a little cooperation
from code. The target of a binding statement (typically a property
of some bit of the UI) must be a dependency property - that is, an
implemented instance of DependencyProperty which can get its value
from external sources. Similarly, the source of the binding must be
able to notify that the value has changed. In the UI layer, this is
typically a DependencyProperty, but in your non-UI objects, you'll
need to implement INotifyPropertyChanged (often called "INPC") and
raise an event whenever values change. Why? Because any class which
has Dependency Properties must derive from DependencyObject, a
constraint which makes no sense in entities, viewmodel and
business-layer classes.</p>

<h3>Basic, Verbose, INPC Example</h3>

<p>Here's an example using INPC in a viewmodel class.</p>

<pre class="brush: csharp;">
public class BasicApproach : INotifyPropertyChanged<br />
{<br />
    private int _level;<br />
    public int Level<br />
    {<br />
        get { return _level; }<br />
        set<br />
        {<br />
            if (_level != value)<br />
            {<br />
                _level = value;<br />
                NotifyPropertyChanged("Level");<br />
            }<br />
        }<br />
    }<br />
<br />
    private string _lastName;<br />
    public string LastName<br />
    {<br />
        get { return _lastName; }<br />
        set<br />
        {<br />
            if (_lastName != value)<br />
            {<br />
                _lastName = value;<br />
                NotifyPropertyChanged("LastName");<br />
                NotifyPropertyChanged("FullName");<br />
            }<br />
        }<br />
    }<br />
<br />
    private string _firstName;<br />
    public string FirstName<br />
    {<br />
        get { return _firstName; }<br />
        set<br />
        {<br />
            if (_firstName != value)<br />
            {<br />
                _firstName = value;<br />
                NotifyPropertyChanged("FirstName");<br />
                NotifyPropertyChanged("FullName");<br />
            }<br />
        }<br />
    }<br />
<br />
    public string FullName<br />
    {<br />
        get { return FirstName + " " + LastName; }<br />
    }<br />
<br />
<br />
    public event PropertyChangedEventHandler PropertyChanged;<br />
<br />
    protected void NotifyPropertyChanged(string propertyName)<br />
    {<br />
        if (PropertyChanged != null)<br />
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));<br />
    }<br />
}
</pre>

<p>Typically I'll refactor this so I have an abstract base class
named <strong>Observable</strong> which contains the interface and
event-raising function. <strong>Nevertheless, this code is tedious
and error-prone</strong>. It's tedious because you have to expand
properties which would have been fine as auto-props. It's
error-prone because you need to pass the string name of the
property to the event. If you make a typo or change the name of the
property without changing the string, binding will never be
notified that the property changed.</p>

<blockquote>
<p>The string-based approach, however, was the best for the
framework developers because it is flexible, very fast, and gives
you the option to implement other approaches on top of it.</p>
</blockquote>

<p>Other folks have come up with their own base classes, many of
which include optimizations to avoid creating so many instances of
the PropertyChangedEventArgs class and include helpful checking
information using reflection when in debug mode. <a
href="http://joshsmithonwpf.wordpress.com/2007/08/29/a-base-class-which-implements-inotifypropertychanged/"
 target="_blank">Here's an example from Josh Smith</a>. One nice
thing about Josh's approach is that takes a performance hit
primarily when in debug mode, not release mode.</p>

<p>There are several other elegant approaches to solving this.
Let's look at the common reflection and lambda approach first.</p>

<h3>Using Reflection and Lambda Expressions</h3>

<p>One particularly slick approach uses both reflection and lambda
expressions to add in a compile-time check on the property
name.</p>

<pre class="brush: csharp;">
public class ReflectionLambdaApproach : INotifyPropertyChanged<br />
{<br />
    private int _level;<br />
    public int Level<br />
    {<br />
        get { return _level; }<br />
        set<br />
        {<br />
            if (_level != value)<br />
            {<br />
                _level = value;<br />
                NotifyPropertyChanged(() =&gt; Level);<br />
            }<br />
        }<br />
    }<br />
<br />
    private string _lastName;<br />
    public string LastName<br />
    {<br />
        get { return _lastName; }<br />
        set<br />
        {<br />
            if (_lastName != value)<br />
            {<br />
                _lastName = value;<br />
                NotifyPropertyChanged(() =&gt; LastName);<br />
                NotifyPropertyChanged(() =&gt; FullName);<br />
            }<br />
        }<br />
    }<br />
<br />
    private string _firstName;<br />
    public string FirstName<br />
    {<br />
        get { return _firstName; }<br />
        set<br />
        {<br />
            if (_firstName != value)<br />
            {<br />
                _firstName = value;<br />
                NotifyPropertyChanged(() =&gt; FirstName);<br />
                NotifyPropertyChanged(() =&gt; FullName);<br />
            }<br />
        }<br />
    }<br />
<br />
    public string FullName<br />
    {<br />
        get { return FirstName + " " + LastName; }<br />
    }<br />
<br />
<br />
<br />
    public event PropertyChangedEventHandler PropertyChanged;<br />
<br />
    public void NotifyPropertyChanged&lt;T&gt;(Expression&lt;Func&lt;T&gt;&gt; property)<br />
    {<br />
        if (PropertyChanged != null)<br />
        {<br />
            var memberExpression = property.Body as MemberExpression;<br />
<br />
            PropertyChanged(this, new PropertyChangedEventArgs(memberExpression.Member.Name));<br />
        }<br />
    }<br />
}
</pre>

<p>Now, as this does use reflection, <strong>it is much slower than
the hard-coded version</strong>. You need to be very aware of this
because the PropertyChanged event can be raised a large number of
times in a class. You'll need to make a decision based on how
<strong>you</strong> will use this in <strong>your</strong>
project.</p>

<p>One optimization to this approach would be to cache the property
descriptor information so you reflect on it only once. Another
common optimization is to <a
href="http://www.sharpfellows.com/post/static-reflection-inotifypropertychanged-2.aspx"
 target="_blank">wrap all the code into a SetProperty (or similar)
method</a> (and this <a
href="http://geekswithblogs.net/brians/archive/2010/08/02/inotifypropertychanged-with-less-code-using-an-expression.aspx"
 target="_blank">update</a>) which handles the property value
checking, assignment, and event raising.</p>

<p>In any case, the amount of code doesn't change significantly
unless you use the SetProperty approach. What you've gained by this
approach is compile-time checking of the property names - a
non-trivial improvement. Another approach which gives us both the
checking and the code reduction and which has gained traction
lately is IL Weaving. This injects property changed information
into the IL rather than into the source code.</p>

<h3>Using IL Weaving</h3>

<p>The ins and outs of IL Weaving is too much to include in this
post. However, I want to refer you to <a
href="http://justinangel.net/AutomagicallyImplementingINotifyPropertyChanged"
 target="_blank">Justin Angel's great post on the topic</a>. Justin
goes through from the top down to what it takes to use MSIL Weaving
in your own project. Be sure to read the comments as well.</p>

<p>When using weaving, you can go back to using auto-properties and
leave out all the INPC gunk. It does have its limitations, though.
In the examples you'll find, it doesn't do anything for dependent
properties like our FullName property. You can certainly expand the
examples to include something like that, but I haven't seen it
done.</p>

<p>Now, despite weaving not doing anything for our FullName
property, that's a heck of a lot cleaner than the other approaches
we've been using. It handles the majority of simple cases where the
properties are not dependent upon each other.</p>

<h3>Summary</h3>

<p>There are tons of other approaches, including this interesting
<a
href="http://www.codeproject.com/KB/WPF/AutoPropertyChanged.aspx"
target="_blank">AutoPropertyChanged approach</a> on codeproject and
this post by <a
href="http://jonas.follesoe.no/2010/01/17/automatic-inpc-using-dynamic-proxy-and-ninject/"
 target="_blank">Jonas on using a dynamic proxy and Ninject</a> to
do the dirty work. This post is by no means a survey of all of
those, but instead a summary of a couple common approaches. I've
seen some really slick implementations that go above and beyond
what I've done here, so be sure to check them out. A simple <a
href="http://www.bing.com/search?q=INotifyPropertyChanged"
target="_blank">bing search for INotifyPropertyChanged</a> will
show you a ton of examples.</p>

<p>In addition, most MVVM frameworks have taken one of these
approaches and built upon it to make your life easier. That's one
of the benefits of picking a MVVM framework when using that pattern
with Silverlight and WPF.</p>

<p>The WPF team is also considering possible approaches for this.
No promises, but it is on their radar :)</p>

<p><strong>If you have a favorite approach I haven't mentioned
here, feel free to link to it or describe it in the
comments.</strong></p>

<p>There's no downloadable source for this post on purpose. Don't
use this code directly, instead go check out some of the more
robust implementations out there. :)</p>
]]></description></item><item><title>Dynamically Generating Controls in WPF and Silverlight</title><author>Pete Brown	</author><link>http://10rem.net/blog/2010/12/08/dynamically-generating-controls-in-wpf-and-silverlight</link><pubDate>Wed, 08 Dec 2010 20:28:47 GMT</pubDate><guid>http://10rem.net/blog/2010/12/08/dynamically-generating-controls-in-wpf-and-silverlight</guid><description><![CDATA[ 
<p>Some of the Windows Forms developers I've spoken to have said
that one thing they want to learn is how to dynamically create
controls in WPF and Silverlight. In this post I'll show you several
different ways to create controls at runtime using Silverlight 4
and WPF 4.</p>

<p>First, we'll start with how to create controls in XAML. From
there, we'll move to dynamically-loaded XAML before we take a look
at using the CLR object equivalents.</p>

<h3>Creating Controls at Design Time in XAML</h3>

<p>Creating controls using the design surface and/or XAML editor is
definitely the easiest way to create your UI. You can use
Expression Blend or Visual Studio, depending upon how creative you
want to be. If you want a more dynamic layout, you can hide and
show panels at runtime.</p>

<p>Here's an example layout:</p>

<pre class="brush: xml;">
&lt;Grid Margin="10"&gt;
    &lt;Grid.ColumnDefinitions&gt;
        &lt;ColumnDefinition Width="100" /&gt;
        &lt;ColumnDefinition Width="*" /&gt;
    &lt;/Grid.ColumnDefinitions&gt;
            
    &lt;Grid.RowDefinitions&gt;
        &lt;RowDefinition Height="Auto" /&gt;
        &lt;RowDefinition Height="Auto" /&gt;
        &lt;RowDefinition Height="Auto" /&gt;
        &lt;RowDefinition Height="*" /&gt;
    &lt;/Grid.RowDefinitions&gt;

    &lt;TextBlock Text="First Name"
                Height="19"
                Margin="0,7,31,4" /&gt;           
    &lt;TextBox x:Name="FirstName"
                Margin="3"
                Grid.Row="0"
                Grid.Column="1" /&gt;
            
    &lt;TextBlock Text="Last Name"
                Margin="0,7,6,3"
                Grid.Row="1"
                Height="20" /&gt;
    &lt;TextBox x:Name="LastName"
                Margin="3"
                Grid.Row="1"
                Grid.Column="1" /&gt;


    &lt;TextBlock Text="Date of Birth"
                Grid.Row="2"
                Margin="0,9,0,0"
                Height="21" /&gt;
    &lt;sdk:DatePicker x:Name="DateOfBirth" 
                    Margin="3"
                    Grid.Row="2"
                    Grid.Column="1" /&gt;


    &lt;Button x:Name="SubmitChanges"
            Grid.Row="3"
            Grid.Column="3"
            HorizontalAlignment="Right"
            VerticalAlignment="Top"
            Margin="3"
            Width="80"
            Height="25"
            Content="Save" /&gt;
&lt;/Grid&gt;
</pre>

<p>That markup creates a layout that looks like this in
Silverlight:</p>

<p><a
href="http://10rem.net/media/72986/Windows-Live-Writer_Dynamically-Generating-Controls-in-WPF-a_CC78_image_2.png"
 target="_blank"><img src="http://10rem.net/media/72991/Windows-Live-Writer_Dynamically-Generating-Controls-in-WPF-a_CC78_image_thumb.png" width="466" height="381" alt="image" border="0" style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px"/></a></p>

<p>Or, if you're using WPF, like this:</p>

<p><a
href="http://10rem.net/media/72996/Windows-Live-Writer_Dynamically-Generating-Controls-in-WPF-a_CC78_image_4.png"
 target="_blank"><img src="http://10rem.net/media/73001/Windows-Live-Writer_Dynamically-Generating-Controls-in-WPF-a_CC78_image_thumb_1.png" width="414" height="252" alt="image" border="0" style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px"/></a></p>

<p>(note that you'll need to remove or remap the "sdk" prefix when
using this XAML in WPF, as the date control is built-in)</p>

<p>Once you're familiar with working in XAML, you can easily modify
the process to load the XAML at runtime to dynamically create
controls.</p>

<h3>Creating Controls at runtime using XAML strings</h3>

<p>In Silverlight, this block of code in the code-behind creates
the same controls at runtime by loading the XAML from a string
using the System.Windows.Markup.XamlReader class. This class
exposes a Load method which (in Silverlight) takes a well-formed
and valid XAML string and returns back a visual tree</p>

<pre class="brush: csharp;">
public MainPage()
{
    InitializeComponent();

    Loaded += new RoutedEventHandler(MainPage_Loaded);
}

void MainPage_Loaded(object sender, RoutedEventArgs e)
{
    CreateControls();
}


private void CreateControls()
{
    string xaml =
    "&lt;Grid Margin='10' " +
        "xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' " + 
        "xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' " + 
        "xmlns:sdk='http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk'&gt;" + 
        "&lt;Grid.ColumnDefinitions&gt;" +
            "&lt;ColumnDefinition Width='100' /&gt;" +
            "&lt;ColumnDefinition Width='*' /&gt;" +
        "&lt;/Grid.ColumnDefinitions&gt;" +

        "&lt;Grid.RowDefinitions&gt;" +
            "&lt;RowDefinition Height='Auto' /&gt;" +
            "&lt;RowDefinition Height='Auto' /&gt;" +
            "&lt;RowDefinition Height='Auto' /&gt;" +
            "&lt;RowDefinition Height='*' /&gt;" +
        "&lt;/Grid.RowDefinitions&gt;" +

        "&lt;TextBlock Text='First Name' Height='19' Margin='0,7,31,4' /&gt;" +
        "&lt;TextBox x:Name='FirstName' Margin='3' Grid.Row='0' Grid.Column='1' /&gt;" +

        "&lt;TextBlock Text='Last Name' Margin='0,7,6,3' Grid.Row='1' Height='20' /&gt;" +
        "&lt;TextBox x:Name='LastName' Margin='3' Grid.Row='1' Grid.Column='1' /&gt;" +

        "&lt;TextBlock Text='Date of Birth' Grid.Row='2' Margin='0,9,0,0' Height='21' /&gt;" +
        "&lt;sdk:DatePicker x:Name='DateOfBirth' Margin='3' Grid.Row='2' Grid.Column='1' /&gt;" +

        "&lt;Button x:Name='SubmitChanges' Grid.Row='3' Grid.Column='3' " +
            "HorizontalAlignment='Right' VerticalAlignment='Top' " +
            "Margin='3' Width='80' Height='25' Content='Save' /&gt;" +
    "&lt;/Grid&gt;";


    UIElement tree = (UIElement)XamlReader.Load(xaml);

    LayoutRoot.Children.Add(tree);
}
</pre>

<p>Note that I needed to add the namespace definitions directly in
this XAML. A chunk of XAML loaded via XamlReader.Load must be
completely self-contained and syntactically correct.</p>

<p>The WPF XamlReader.Load call is slightly different as it has no
overload which would take a string. Instead, it takes an XmlReader
as one form of parameter:</p>

<pre class="brush: csharp;">
StringReader stringReader = new StringReader(xaml);
XmlReader xmlReader = XmlReader.Create(stringReader);

UIElement tree = (UIElement)XamlReader.Load(xmlReader);

LayoutRoot.Children.Add(tree);
</pre>

<p>&nbsp;</p>

<p>This technique also works for loading chunks of XAML from a file
on the local machine, or as the result of a database query. It's
also helpful for enabling the use of constants (like the extended
color set) that are recognized by XAML parser in Silverlight, but
not from code.</p>

<p>The more typical approach to dynamically creating controls,
however, is to simply use the CLR objects.</p>

<h3>Creating Controls at runtime using Code and CLR Objects</h3>

<p>Everything you do in XAML can also be done from code. XAML is a
representation of CLR objects, rather than a markup language that
abstracts the underlying objects. Creating controls from code tends
to be more verbose than doing the same from XAML. However, it is a
familiar approach for Windows Forms developers, and a great way to
handle dynamic UI.</p>

<pre class="brush: csharp;">
private void CreateControlsUsingObjects()
{
    // &lt;Grid Margin="10"&gt;
    Grid rootGrid = new Grid();
    rootGrid.Margin = new Thickness(10.0);
            
    // &lt;Grid.ColumnDefinitions&gt;
    //   &lt;ColumnDefinition Width="100" /&gt;
    //   &lt;ColumnDefinition Width="*" /&gt;
    //&lt;/Grid.ColumnDefinitions&gt;

    rootGrid.ColumnDefinitions.Add(
        new ColumnDefinition() { Width = new GridLength(100.0) });
    rootGrid.ColumnDefinitions.Add(
        new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });

    //&lt;Grid.RowDefinitions&gt;
    //  &lt;RowDefinition Height="Auto" /&gt;
    //  &lt;RowDefinition Height="Auto" /&gt;
    //  &lt;RowDefinition Height="Auto" /&gt;
    //  &lt;RowDefinition Height="*" /&gt;
    //&lt;/Grid.RowDefinitions&gt;

    rootGrid.RowDefinitions.Add(
        new RowDefinition() { Height = GridLength.Auto });
    rootGrid.RowDefinitions.Add(
        new RowDefinition() { Height = GridLength.Auto });
    rootGrid.RowDefinitions.Add(
        new RowDefinition() { Height = GridLength.Auto });
    rootGrid.RowDefinitions.Add(
        new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });

    //&lt;TextBlock Text="First Name"
    //           Height="19"
    //           Margin="0,7,31,4" /&gt;

    var firstNameLabel = CreateTextBlock("First Name", 19, new Thickness(0, 7, 31, 4), 0, 0);
    rootGrid.Children.Add(firstNameLabel);

    //&lt;TextBox x:Name="FirstName"
    //         Margin="3"
    //         Grid.Row="0"
    //         Grid.Column="1" /&gt;

    var firstNameField = CreateTextBox(new Thickness(3), 0, 1);
    rootGrid.Children.Add(firstNameField);

    //&lt;TextBlock Text="Last Name"
    //           Margin="0,7,6,3"
    //           Grid.Row="1"
    //           Height="20" /&gt;

    var lastNameLabel = CreateTextBlock("Last Name", 20, new Thickness(0, 7, 6, 3), 1, 0);
    rootGrid.Children.Add(lastNameLabel);

            
    //&lt;TextBox x:Name="LastName"
    //         Margin="3"
    //         Grid.Row="1"
    //         Grid.Column="1" /&gt;

    var lastNameField = CreateTextBox(new Thickness(3), 1, 1);
    rootGrid.Children.Add(lastNameField);


    //&lt;TextBlock Text="Date of Birth"
    //           Grid.Row="2"
    //           Margin="0,9,0,0"
    //           Height="21" /&gt;

    var dobLabel = CreateTextBlock("Date of Birth", 21, new Thickness(0, 9, 0, 0), 2, 0);
    rootGrid.Children.Add(dobLabel);

    //&lt;DatePicker x:Name="DateOfBirth"
    //            Margin="3"
    //            Grid.Row="2"
    //            Grid.Column="1" /&gt;

    DatePicker picker = new DatePicker();
    picker.Margin = new Thickness(3);
    Grid.SetRow(picker, 2);
    Grid.SetColumn(picker, 1);
    rootGrid.Children.Add(picker);

    //&lt;Button x:Name="SubmitChanges"
    //        Grid.Row="3"
    //        Grid.Column="3"
    //        HorizontalAlignment="Right"
    //        VerticalAlignment="Top"
    //        Margin="3"
    //        Width="80"
    //        Height="25"
    //        Content="Save" /&gt;

    Button button = new Button();
    button.HorizontalAlignment = HorizontalAlignment.Right;
    button.VerticalAlignment = VerticalAlignment.Top;
    button.Margin = new Thickness(3);
    button.Width = 80;
    button.Height = 25;
    button.Content = "Save";
    Grid.SetRow(button, 3);
    Grid.SetColumn(button, 1);
    rootGrid.Children.Add(button);

    LayoutRoot.Children.Add(rootGrid);
}

private TextBlock CreateTextBlock(string text, double height, Thickness margin, int row, int column)
{
    TextBlock tb = new TextBlock() 
        { Text = text, Height = height, Margin = margin };
    Grid.SetColumn(tb, column);
    Grid.SetRow(tb, row);

    return tb;
}

private TextBox CreateTextBox(Thickness margin, int row, int column)
{
    TextBox tb = new TextBox() { Margin = margin };
    Grid.SetColumn(tb, column);
    Grid.SetRow(tb, row);

    return tb;
}
</pre>

<p>You'll see the code is only slightly more verbose when expanded
out. The two helper functions help minimize that. In the code, I
create the entire branch of the visual tree before I add it to the
root. Doing this helps minimize layout cycles you'd otherwise have
if you added each item individually to the root.</p>

<p>I tend to put any UI interaction inside the Loaded event.
However, you could place this same code inside the constructor,
after the InitializeComponent call. As your code gets more complex,
and relies on other UI elements to be initialized and loaded,
you'll want to be smart about which function you use.</p>

<h4>Handling Events</h4>

<p>If you want to handle events, like button clicks, you'd do that
like any other .NET event handler:</p>

<pre class="brush: csharp;">
{
    Button button = new Button();
    ...
    button.Click += new RoutedEventHandler(button_Click);

    LayoutRoot.Children.Add(rootGrid);
}

void button_Click(object sender, RoutedEventArgs e)
{
    ...
}
</pre>

<p>Creating controls from code doesn't mean you lose the valuable
ability to data bind. In some cases, especially where the binding
source is hard to reference from XAML, binding is easier in
code.</p>

<h4>Binding Dynamically Created Controls</h4>

<p>We haven't used any binding yet, so we'll need to create a
binding source. For that, I created a simple shared project that
targets Silverlight 4. It's a Silverlight class library project and
is used by both the WPF and Silverlight examples. <strong>Remember,
to use it from WPF 4 (without any additions), you'll need to use a
file reference to the compiled DLL, not a project
reference</strong>.</p>

<p>Inside that project, I created a single ViewModel class named
ExampleViewModel.</p>

<pre class="brush: csharp;">
public class ExampleViewModel : INotifyPropertyChanged
{
    private string _lastName;
    public string LastName
    {
        get { return _lastName; }
        set { _lastName = value; NotifyPropertyChanged("LastName"); }
    }

    private string _firstName;
    public string FirstName
    {
        get { return _firstName; }
        set { _firstName = value; NotifyPropertyChanged("FirstName"); }
    }

    private DateTime _dateOfBirth;
    public DateTime DateOfBirth
    {
        get { return _dateOfBirth; }
        set { _dateOfBirth = value; NotifyPropertyChanged("DateOfBirth"); }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void NotifyPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}
</pre>

<p>Inside the code-behind (this is a demo, after all) of the Window
(or Page), initialize the viewmodel class:</p>

<pre class="brush: csharp;">
private ExampleViewModel _vm = new ExampleViewModel();

public MainWindow()
{
    _vm.LastName = "Brown";
    _vm.FirstName = "Pete";
    _vm.DateOfBirth = DateTime.Parse("Jan 1, 1910");

    InitializeComponent();

    ...
}
</pre>

<p>Once that is done, we can create an example binding. I'm going
to use the First Name TextBox and set up two-way binding with the
FirstName property of the ExampleViewModel instance.</p>

<pre class="brush: csharp;">
var firstNameField = CreateTextBox(new Thickness(3), 0, 1);
Binding firstNameBinding = new Binding();
firstNameBinding.Source = _vm;
firstNameBinding.Path = new PropertyPath("FirstName");
firstNameBinding.Mode = BindingMode.TwoWay;
firstNameField.SetBinding(TextBox.TextProperty, firstNameBinding);          

rootGrid.Children.Add(firstNameField);
</pre>

<p>The same approach to expressing binding also works in XAML. It's
just that we have a binding markup extension that makes the process
easier.</p>

<p>One thing that tripped me up in this example was I passed in
TextBlock.TextProperty to the SetBinding call. <strong>That's a
valid dependency property, so it compiles just fine</strong>. In
WPF, that fails silently, even when you have verbose binding
debugging turned on. In Silverlight, it throws a catastrophic error
(without any additional information). That catastrophic error made
me look more closely at the call, ultimately leading to the
fix.</p>

<p>To bind controls added using dynamically-loaded XAML, you'll
need to provide a valid Name to each control you want to reference,
then use FindName after loading to get a reference to the control.
From there, you can using the Binding object and SetBinding method.
Of course, you can also embed the binding statements directly in
the XAML if you wish to do a little string manipulation.</p>

<h3>Summary</h3>

<p>So, we've seen that there are three different ways you can
display controls in Silverlight and WPF.</p>

<ul>
<li>Use the design surface / XAML Editor / Blend and create them
prior to compiling</li>

<li>Load XAML at runtime</li>

<li>Use CLR Objects at runtime</li>
</ul>

<p>Each way is useful in different scenarios, and also has
different performance characteristics. XAML parsing is surprisingly
efficient and the XAML can be stored in a large text field in a
single row in a database or as a loose file on the file system, for
example.</p>

<p>For additional information on the layout system and the visual
tree, please see the following</p>

<ul>
<li><a href="http://manning.com/pbrown" target="_blank">My book on
Silverlight 4, chapter 6 on Layout</a></li>

<li><a
href="http://www.amazon.com/WPF-4-Unleashed-Adam-Nathan/dp/0672331195/"
 target="_blank">WPF 4 Unleashed by Adam Nathan</a></li>

<li><a href="http://msdn.microsoft.com/en-us/library/ms753391.aspx"
target="_blank">MSDN: Trees in WPF</a> (free)</li>
</ul>

<p>The attached zip file contains source for both Silverlight 4 and
WPF 4.</p>
]]></description></item><item><title>Windows Forms to XAML: Do I really need a Designer for Silverlight or WPF Applications?</title><author>Pete Brown	</author><link>http://10rem.net/blog/2010/11/19/windows-forms-to-xaml-do-i-really-need-a-designer-for-silverlight-or-wpf-applications</link><pubDate>Fri, 19 Nov 2010 06:25:24 GMT</pubDate><guid>http://10rem.net/blog/2010/11/19/windows-forms-to-xaml-do-i-really-need-a-designer-for-silverlight-or-wpf-applications</guid><description><![CDATA[ 
<p>I've made it a personal goal this coming year to help Windows
Forms developers (who want to move) move to Silverlight and/or
WPF.</p>

<p>A common sticking point for development shops planning to adopt
Silverlight or WPF after years of work in something like Windows
Forms, is that they feel they need a design professional on-team in
order to build the same quality apps they've been used to building.
After looking at some of the <a
href="http://10rem.net/blog/2010/02/10/the-book-of-wpf"
target="_blank">amazing consumer and ISV experiences</a> being
developed in Silverlight and WPF, I can certainly see why folks
might get this impression.</p>

<p>The blank slate you get when first developing WPF or Silverlight
applications can be intimidating. Suddenly, the sky's the limit.
It's <strong>like you've worked with a single pencil your whole
life, and have been suddenly delivered a huge box of
crayons</strong>. Rather than just pick the black crayon and
continue to draw much like you did with the pencil (with some
obvious adjustments to account for the differences between a waxy
crayon and a hard pencil), you feel like you really must use the
whole set you've been given just to keep up with the Joneses.</p>

<p><img src="http://10rem.net/media/69595/Windows-Live-Writer_996899d19251_147D6_image_9.png" width="350" height="262" alt="Original: http://www.flickr.com/photos/31081559@N04/3275001259/" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></p>

<p>At that point, many of us lock up and say simply "I can't do
this. I don't know where to start" or "I've seen some awesome
drawings using all these crayons, and I know I'm not yet good with
colors". It's a crisis of self-confidence, and it gets in the way
of learning something new. In many cases, the developers simply say
that in order to use this new box of crayons, they must have an
artist working with them. Otherwise, they're just going to stick
with their pencil so as not to embarrass themselves with their
color selection and technique.</p>

<p>While most any project in any technology (ASP.NET, Windows
Forms, WPF, whatever) will benefit from good user experience
designers and graphics designers, they are certainly <strong>not a
requirement when you want to build the same comfortable battleship
gray type apps (or ghost white) you're building in Windows Forms
today.</strong></p>

<p>Here's a representative business application in-development.
Nothing special here: a treeview, a menu, status bar, a couple
headers, a few fields and a datagrid. Very few companies would use
a design professional when creating this (not saying that's ok,
just typical) in Windows Forms. Those same companies or project
teams wouldn't need a design professional to create this in WPF or
Silverlight. In fact, throw a couple icons in there and a toolbar,
and this looks very much like the Windows Forms 1.1 apps I built
near the start of the decade.</p>

<p><a
href="http://10rem.net/media/69600/Windows-Live-Writer_996899d19251_147D6_image_6.png"
 target="_blank"><img src="http://10rem.net/media/69605/Windows-Live-Writer_996899d19251_147D6_image_thumb_2.png" width="500" height="373" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></a></p>

<p>There are no fancy carousels, no rotating widgets, no special
effects. In fact, there are very few animations to begin with.
Sure, once you learn the platform and some good UX patterns, you
can augment your application with nice transitions and subtle
animations, but it's not a requirement to get in the door. In fact,
it's never really a requirement unless you get to a point where you
want to make it so. <strong>It's your (and your customer's)
choice</strong>.</p>

<h3>Editor Support and Expression Blend</h3>

<p>Another related concern is that developers think they have to
use Expression Blend to do any UI work. Here's a screen shot of the
VS2010 design surface, with a typical menu being built using the
design tools. The XAML is shown at the bottom, but I've been using
the design surface in this example. Not only is it productive, it's
a great way to learn XAML syntax.</p>

<p><a
href="http://10rem.net/media/69610/Windows-Live-Writer_996899d19251_147D6_image_2.png"
 target="_blank"><img src="http://10rem.net/media/69615/Windows-Live-Writer_996899d19251_147D6_image_thumb.png" width="500" height="394" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></a></p>

<p>While I do enjoy working in Expression Blend, it isn't something
you have to use when building these types of applications. The
VS2010 editor's design surface combined with the ability to
directly edit XAML is sufficient for all the Windows Forms
equivalent design work you'll have to do. It will even help you
with binding syntax, both in the XAML editor and, as shown here, on
the design surface.</p>

<p><a
href="http://10rem.net/media/69620/Windows-Live-Writer_996899d19251_147D6_image_11.png"
 target="_blank"><img src="http://10rem.net/media/69625/Windows-Live-Writer_996899d19251_147D6_image_thumb_4.png" width="520" height="381" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></a></p>

<p>So, if you were able to design your Windows Forms apps using
just the editor, you should feel comfortable that you'll be able to
do the same with WPF or Silverlight in Visual Studio 2010. The
property names will be a little different, and the concepts will
take some adjusting to (I'm working on helping with all that), but
the tooling is definitely there for you.</p>

<p>Now. If you want to take that application and create a truly
differentiated user experience, then yes, you'll want design
professionals working with you from the very start of the project,
and you'll want someone working in Blend. The difference here is
that WPF and Silverlight actually provide a good platform for you
to work with those professionals while creating that experience
whereas Windows Forms was not designed with that in mind.</p>

<p>(hint, install the Silverlight 4 tools to get some enhancements
to the shared WPF and Silverlight editor)</p>

<h3>Conclusion</h3>

<p>Don't feel that just because it's Silverlight or WPF, you have
to be super creative in your application design. In fact,
<strong>your first couple projects should be conservative, using
user experience patterns you've honed during years of Windows Forms
experience</strong>.</p>

<p>If you're getting away without designers today, and
<strong>don't need to create a truly differentiated or premium
experience</strong>, then you don't need designers on your team
when you move to WPF or Silverlight. The WPF editor is good enough
for business application developers to do the vast majority of
their UI layout work, dropping into the XAML editor from time to
time only when it is the faster approach for you.</p>
]]></description></item><item><title>Creating an Office Communicator Application for Do Not Disturb</title><author>Pete Brown	</author><link>http://10rem.net/blog/2010/10/17/creating-an-office-communicator-application-for-do-not-disturb</link><pubDate>Mon, 18 Oct 2010 01:22:35 GMT</pubDate><guid>http://10rem.net/blog/2010/10/17/creating-an-office-communicator-application-for-do-not-disturb</guid><description><![CDATA[ 
<p>When meeting with other people at Microsoft, my computer is also
my phone. I rely on Office Communicator 2007 R2 more than many
other applications.</p>

<p>Family members wandering into my home office can't really tell
I'm on a call unless I happen to be talking right then. I normally
have my headphones on anyway, and I use my Samson mic for voice.
Usually my wife stands out of camera range and mimes "Are you on
the phone?". My kids just wander in regardless, often half-dressed,
which makes for some pretty funny meetings ;)</p>

<p>So, I thought it would be neat to create a little application
that could show "On-Air" or similar when parked on a small monitor
(think a USB MIMO display) facing towards the door. When I build my
new office in the next room, I'll actually stick this outside the
door so people can see before wandering in.</p>

<p>I haven't purchased the MIMO yet, as I wanted to do a little
proof-of-concept project first. The app described in this post is
that proof-of-concept.</p>

<h3>Project Setup</h3>

<p>Start up a new WPF application. I named mine
"PeteBrown.CommunicatorDisplay". Next, add a reference to the
communicator API.</p>

<p>To integrate with communicator, you'll want to download the <a
href="http://www.microsoft.com/downloads/en/details.aspx?familyid=ED1CCE45-CC22-46E1-BD50-660FE6D2C98C&amp;displaylang=en"
 target="_blank">Microsoft Office Communicator 2007 SDK</a>. Once
installed, you can browse to the DLLs inside the Add Reference
dialog for your project.</p>

<p><a
href="http://10rem.net/media/68615/WindowsLiveWriter_CreatinganOfficeCommunicatorApplicationt_1184C_image_4.png"
 target="_blank"><img src="http://10rem.net/media/68620/WindowsLiveWriter_CreatinganOfficeCommunicatorApplicationt_1184C_image_thumb_1.png" width="504" height="313" alt="image" border="0" style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px"/></a></p>

<p>CommunicatorAPI is the standard API which can be used to
interact with communicator, showing dialogs etc.
CommunicatorPrivate provides much of the same functionality, but
without displaying any UI. Both libraries were installed to
<strong>c:\Program Files(x86)\Microsoft Office
Communicator\SDK</strong></p>

<h3>Working with the API - the CommunicatorService Class</h3>

<p>For this little app, I'll need to subscribe to an event that
will tell me when my status changes. The event, in this case is
OnMyStatusChange. To keep the code somewhat cleaner, I decided to
package up all the Communicator interaction (of which there is
little in this app), including the wiring of OnMyStatusChange, into
a single CommunicatorService class.</p>

<pre class="brush: csharp;">
public enum CommunicatorStatus
{
    Available,
    OnPhone
}

public class CommunicatorService : IDisposable
{
    private Messenger _messenger;

    public CommunicatorService()
    {
        _messenger = new Messenger();
        _messenger.OnMyStatusChange += new DMessengerEvents_OnMyStatusChangeEventHandler(OnMyStatusChange);

        //TODO: Map startup status
    }

    private void OnMyStatusChange(int hr, MISTATUS mMyStatus)
    {
        System.Diagnostics.Debug.WriteLine(mMyStatus.ToString());
        switch (mMyStatus)
        {
            case MISTATUS.MISTATUS_IN_A_CONFERENCE:
            case MISTATUS.MISTATUS_IN_A_MEETING:
            case MISTATUS.MISTATUS_ON_THE_PHONE:
                Status = CommunicatorStatus.OnPhone;
                break;

            case MISTATUS.MISTATUS_ONLINE: 
            case MISTATUS.MISTATUS_OFFLINE:
            case MISTATUS.MISTATUS_AWAY:
                Status = CommunicatorStatus.Available;
                break;

        }
    }

    public event EventHandler StatusChanged;
    private CommunicatorStatus _status;
    public CommunicatorStatus Status
    {
        get { return _status; }
        set
        {
            if (_status != value)
            {
                _status = value;

                if (StatusChanged != null)
                    StatusChanged(this, EventArgs.Empty);
            }
        }
    }

    public void Dispose()
    {
        if (_messenger != null)
        {
            _messenger.OnMyStatusChange -= OnMyStatusChange;
            _messenger = null;
        }
    }

    ~CommunicatorService()
    {
        if (_messenger != null)
            Dispose();
    }
}
</pre>

<p>Note that I implement IDisposable here. I wanted to clean up the
Communicator hooks. It's very likely overkill, but if I end up
doing more with this class in the future, I'll be class it's in
place.</p>

<p>Once I had the service set up, I create a view model class to
act as the glue between the view and the service.</p>

<h3>The ViewModel</h3>

<p>This application has only a single viewmodel class. That's due
to having only a single view. This class is responsible for
creating the communicator service instance, and for handling the
StatusChanged event. It then takes the information from the service
and maps it to a set of bindable properties used by the UI.</p>

<pre class="brush: csharp;">
public class MainViewModel : Observable
{
    private CommunicatorService _communicatorService;

    public MainViewModel()
    {
        _communicatorService = new CommunicatorService();
        _communicatorService.StatusChanged += new EventHandler(OnCommunicatorStatusChanged);
    }

    void OnCommunicatorStatusChanged(object sender, EventArgs e)
    {
        switch (_communicatorService.Status)
        {
            case CommunicatorStatus.Available:
                StatusText = "Available";
                DoNotDisturb = false;
                break;

            case CommunicatorStatus.OnPhone:
                StatusText = "On the Phone";
                DoNotDisturb = true;
                break;
        }
    }

    private string _statusText = string.Empty;
    public string StatusText
    {
        get { return _statusText; }
        set
        {
            if (_statusText != value)
            {
                _statusText = value;
                NotifyPropertyChanged("StatusText");
            }
        }
    }

    private bool _doNotDisturb = false;
    public bool DoNotDisturb
    {
        get { return _doNotDisturb; }
        set
        {
            if (_doNotDisturb != value)
            {
                _doNotDisturb = value;
                NotifyPropertyChanged("DoNotDisturb");
            }
        }
    }
}
</pre>

<p>As is my usual approach, I created a simple base class named
"Observable" to handle the INotifyPropertyChanged cruft.</p>

<pre class="brush: csharp;">
public abstract class Observable : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void NotifyPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}
</pre>

<h3>The User Interface</h3>

<p>The UI is pretty basic. If I'm not to be disturbed, the color is
Red. If I'm available, the color is green. In both cases, the
status text is displayed in white against this background
color.</p>

<pre class="brush: xml;">
&lt;Window x:Class="PeteBrown.CommunicatorDisplay.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:controls="clr-namespace:System.Windows.Controls;assembly=PresentationFramework"
        Title="MainWindow" Height="400" Width="800"&gt;
    
    &lt;Window.Resources&gt;
        &lt;controls:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" /&gt;
    &lt;/Window.Resources&gt;
    
    &lt;Grid&gt;
        &lt;Rectangle Fill="DarkGreen" /&gt;
        &lt;Rectangle Fill="DarkRed"
                   Visibility="{Binding DoNotDisturb, Converter={StaticResource BooleanToVisibilityConverter}}" /&gt;
        &lt;TextBlock Text="{Binding StatusText}"
                   HorizontalAlignment="Center"
                   VerticalAlignment="Center"
                   FontSize="120"
                   Foreground="White"
                   TextWrapping="Wrap" /&gt;
    &lt;/Grid&gt;
&lt;/Window&gt;
</pre>

<p>I handled the display of the red background using the built-in
BooleanToVisibilityConverter in WPF in a binding statement against
the DoNotDisturb property of the viewmodel. The text displayed
comes from the StatusText property of the viewmodel. The green
background is always there, but it is revealed only when the red
background is collapsed.</p>

<p>The Window is sized fro the typical 800x400 resolution of some
of the mini USB displays. Some other displays have different
resolutions; adjust as necessary.</p>

<p>The code-behind for the window is pretty brief:</p>

<pre class="brush: csharp;">
public partial class MainWindow : Window
{
    MainViewModel _vm;

    public MainWindow()
    {
        InitializeComponent();

        Loaded += new RoutedEventHandler(MainWindow_Loaded);
    }

    void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
        _vm = new MainViewModel();
        DataContext = _vm;
    }
}
</pre>

<p>All I do there is instantiate the viewmodel and assign it as the
DataContext for the window.</p>

<h3>Test Run</h3>

<p>To test, I called my mobile phone from communicator. Within a
couple seconds, the WPF application picked up and displayed the
correct status:</p>

<p><a
href="http://10rem.net/media/68625/WindowsLiveWriter_CreatinganOfficeCommunicatorApplicationt_1184C_image_6.png"
 target="_blank"><img src="http://10rem.net/media/68630/WindowsLiveWriter_CreatinganOfficeCommunicatorApplicationt_1184C_image_thumb_2.png" width="500" height="163" alt="image" border="0" style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px"/></a></p>

<p>Once I hung up, I got the expected "Available" status. Remember,
I don't care if the status is "Away" or anything like that; this is
just to tell people whether or not it's ok to wander into the
office and ask me a question</p>

<p><a
href="http://10rem.net/media/68635/WindowsLiveWriter_CreatinganOfficeCommunicatorApplicationt_1184C_image_8.png"
 target="_blank"><img src="http://10rem.net/media/68640/WindowsLiveWriter_CreatinganOfficeCommunicatorApplicationt_1184C_image_thumb_3.png" width="500" height="250" alt="image" border="0" style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px"/></a></p>

<p>That's all there is to it from a proof-of-concept level of
application.</p>

<h3>Wrap-Up</h3>

<p>The Communicator API is simple to use from a WPF application,
even without using some of the wrapper WPF presence controls.</p>

<p>Of course, this is a proof-of-concept. To make this more robust,
I'll want to add in code to handle disconnection and shutdown, as
well as other events. I'll also need to handle other statuses to
ensure I have all the types of meetings covered. I'd want to check
the status at startup and make sure I have that handled as well.
Finally, this whole application could be refactored to use a custom
control with visual states for each of the communicator statuses
rather than the DoNotDisturb boolean value.</p>

<p>Oh, and plugging in other apps would be nice. For example, if
Camtasia is running, it would be nice to automatically set this to
stay "Recording" or something like that.</p>
]]></description></item><item><title>Custom Placement within an ItemsControl in WPF</title><author>Pete Brown	</author><link>http://10rem.net/blog/2010/09/16/custom-placement-within-an-itemscontrol-in-wpf</link><pubDate>Thu, 16 Sep 2010 21:33:11 GMT</pubDate><guid>http://10rem.net/blog/2010/09/16/custom-placement-within-an-itemscontrol-in-wpf</guid><description><![CDATA[ 
<p>I've been tripped up on a problem in Shoebox Scan for several
weeks now. I'll pick it up for an hour or two on a Friday, get
nowhere, and put it down until later the next week. Today, I
finally figured out what the problem is. (Yes, I have been piddling
with this application since early this year. I'm pretty sure <a
href="http://hanselman.com/" target="_blank">Scott</a> has a
special ulcer just for me and Shoebox scan &lt;g&gt;)</p>

<h3>Background</h3>

<p>I rewrote Shoebox Scan so I could make the code follow modern <a
href="http://windowsclient.net/" target="_blank">WPF</a> coding and
design practices. There were some areas of really tight coupling
between some of the UI elements and the backing store that were a
constant source of churn whenever I made a change. I won't say it
was a disaster, but it was a mess. The part of the code had to do
with the selection of regions in the image for purposes of rotating
and cropping.</p>

<p>Here's a work-in-progress screenshot showing two selection
regions on a scanned image. The adorners are turned off for the
moment because I thought they were the problem. Without the
adorners, you can move the regions around. With the adorners, you
can move everything around, plus rotate and resize to select a
region from the image to save to a file.</p>

<p><a
href="http://10rem.net/media/67542/WindowsLiveWriter_CustomPlacementwithinanItemsControlinWPF_EE53_image_2.png"
 target="_blank"><img src="http://10rem.net/media/67547/WindowsLiveWriter_CustomPlacementwithinanItemsControlinWPF_EE53_image_thumb.png" width="526" height="324" alt="image" border="0" style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px"/></a></p>

<h3>Refactoring</h3>

<p>So, I refactored it to use MVVM with binding in the UI. Rather
than have these other controls injecting everything via code, I was
able to move the UI into XAML. Rather than have code which added
and removed regions, I was able to use a plain old
ItemsControl&nbsp; to represent them on-screen, and a data template
to define the appearance. I'll probably retemplate a listbox or
derive my own control from Selector later.</p>

<p><a
href="http://10rem.net/media/67552/WindowsLiveWriter_CustomPlacementwithinanItemsControlinWPF_EE53_image_6.png"
 target="_blank"><img src="http://10rem.net/media/67557/WindowsLiveWriter_CustomPlacementwithinanItemsControlinWPF_EE53_image_thumb_2.png" width="575" height="405" alt="image" border="0" style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px"/></a></p>

<p>You wouldn't normally think of an ItemsControl in this context.
ItemsControls are usually thought of for lists of data in some
structured format. This is free form: each item can be a different
size, rotation and location.</p>

<p>Inside the data template, I bound the <strong>root grid of the
template</strong> to the Left, Top, Width, and Height of the
SelectionRegion.</p>

<h3>The Problem</h3>

<p>While the ItemsControl is actually perfectly suited to this, The
problem I ran into was that no matter what I did, I could not get
the regions to move from the top left. I could see that the
properties were correct in the viewmodel.</p>

<p>In the DataTemplate, I had set up a root Grid, and bound the
Canvas.Left and Canvas.Top properties to the appropriate properties
on the SelectionRegion model object. In the debugger, I verified
that the properties were being updated, that there were no binding
problems. I also did the usual replacement of the ItemsPanel with a
canvas set to stretch in both directions. Still no go. Despite the
frustration of seeing everything correct in the debugger, the
visuals weren't correct.</p>

<h3>The Debugging (well, the last bit of it, anyway)</h3>

<p>I cracked open <a href="http://snoopwpf.codeplex.com"
target="_blank">Snoop</a> and looked at the tree. It occurred to me
that the problem might be with the ContentPresenter's positioning
or sizing.</p>

<p><a
href="http://10rem.net/media/67562/WindowsLiveWriter_CustomPlacementwithinanItemsControlinWPF_EE53_image_8.png"
 target="_blank"><img src="http://10rem.net/media/67567/WindowsLiveWriter_CustomPlacementwithinanItemsControlinWPF_EE53_image_thumb_3.png" width="307" height="302" alt="image" border="0" style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px"/></a></p>

<p>Sure enough, when I looked at the ActualHeight and ActualWidth,
I saw that the content presenter was sized to the individual item.
This seems obvious in retrospect, but it took a while to find
it.</p>

<h3>The Solution</h3>

<p>The solution, of course, was to <strong>set the
ItemContainerStyle and bind that to the Left, Top, Width and
Height</strong>. The resulting ItemsControl with the appropriate
templates, looks like this:</p>

<pre class="brush: xml;">
&lt;ItemsControl x:Name="Selections"
              ItemsSource="{Binding Regions}"
              HorizontalAlignment="Stretch"
              VerticalAlignment="Stretch"&gt;
    &lt;ItemsControl.ItemsPanel&gt;
        &lt;ItemsPanelTemplate&gt;
            &lt;Canvas HorizontalAlignment="Stretch"
                    VerticalAlignment="Stretch"/&gt;
        &lt;/ItemsPanelTemplate&gt;
    &lt;/ItemsControl.ItemsPanel&gt;

    &lt;ItemsControl.ItemContainerStyle&gt;
        &lt;Style TargetType="ContentPresenter"&gt;
            &lt;Setter Property="Canvas.Left"
                    Value="{Binding CalculatedNormalLeft}" /&gt;
            &lt;Setter Property="Canvas.Top"
                    Value="{Binding CalculatedNormalTop}" /&gt;
            &lt;Setter Property="Width"
                    Value="{Binding Width}" /&gt;
            &lt;Setter Property="Height"
                    Value="{Binding Height}" /&gt;
        &lt;/Style&gt;
    &lt;/ItemsControl.ItemContainerStyle&gt;
    
    &lt;ItemsControl.ItemTemplate&gt;
        &lt;DataTemplate&gt;
            &lt;Grid HorizontalAlignment="Stretch"
                  VerticalAlignment="Stretch"&gt;

            &lt;controls:MoveThumb Cursor="SizeAll"
                                Template="{StaticResource MoveThumbTemplate}" /&gt;

                &lt;Rectangle Fill="Blue"
                           Opacity="0.1"
                           IsHitTestVisible="False"
                           Stretch="Fill" /&gt;

                &lt;TextBlock Foreground="#ffffffff"
                           FontSize="24"
                           FontWeight="Bold"
                           FontFamily="Segoe UI"
                           Text="{Binding Caption}"
                           IsHitTestVisible="False"
                           Margin="10,0,10,0"
                           HorizontalAlignment="Center"
                           VerticalAlignment="Center"&gt;
                    &lt;TextBlock.Effect&gt;
                        &lt;DropShadowEffect Opacity="1"
                                          BlurRadius="4"
                                          Color="Black"
                                          ShadowDepth="0" /&gt;
                    &lt;/TextBlock.Effect&gt;
                &lt;/TextBlock&gt;

                &lt;!--&lt;controls:DesignerItemDecorator x:Name="ItemDecorator"
                                                ShowDecorator="True" /&gt;--&gt;

                &lt;Grid.RenderTransform&gt;
                    &lt;RotateTransform CenterX="0.5"
                                     CenterY="0.5"
                                     Angle="{Binding RotationAngle}" /&gt;
                &lt;/Grid.RenderTransform&gt;

            &lt;/Grid&gt;

        &lt;/DataTemplate&gt;
    &lt;/ItemsControl.ItemTemplate&gt;
&lt;/ItemsControl&gt;
</pre>

<p>I'm posting this in case someone else tries to bend an
ItemsControl in a similar way, and runs into problems with
positioning. Now I can go back to solving the hard problems around
rotation and cropping :)</p>
]]></description></item></channel></rss>
