» Publishers, Monetize your RSS feeds with FeedShow: More infos (Show/Hide Ads)








One of the pain points in MVVM development is controlling input focus from ViewModel objects. A common scenario is when a validation error occurs, and focus needs to move to the control that is bound to the property in error. This makes it easier for the user to immediately fix the validation problem.
A while ago, Dr. WPF shared a solution to the WPF Disciples that involves hijacking the VM’s IDataErrorInfo implementation and doing some hacky magic that results in focus being sent to the correct control. While a brilliant solution, I preferred finding a more formal, less hacky solution. This blog post presents the implementation that I’ve thrown together, with help from the WPF Disciples over the past few days.
In a ViewModel object, you must implement my IFocusMover interface.
public event EventHandler MoveFocus;
void RaiseMoveFocus(string focusedProperty)
{
var handler = this.MoveFocus;
if (handler != null)
{
var args = new MoveFocusEventArgs(focusedProperty);
handler(this, args);
}
}
The MoveFocus event should be raised when the VM object determines that input focus needs to be sent to the control bound to the ‘focused property.’ For example, if the FirstName property of an object is deemed invalid, you would call the RaiseMoveFocus method, passing “FirstName” as the focused property argument. In the demo application, this results in the TextBox whose Text is bound to the FirstName property to get input focus.
Now let’s shift our attention to the View to see how a control is configured to be able to receive focus. The only thing you must do is use a custom Binding object that I made, called FocusBinding. That class relies on Philipp Sumi’s BindingDecoratorBase class, which allows you to create a custom Binding that can override the all-important ProvideValue method (inherited from MarkupExtension).
public override object ProvideValue(IServiceProvider provider)
{
DependencyObject elem;
DependencyProperty prop;
if (base.TryGetTargetItems(provider, out elem, out prop))
{ FocusController.SetFocusableProperty(elem, prop); }
return base.ProvideValue(provider);
}
You use the FocusBinding in XAML like this:
<TextBox
Text=”{jas:FocusBinding Path=FirstName, ValidatesOnDataErrors=True}”
/>
The ValidatesOnDataErrors property setting is not required, but is used in the demo app to enable support for validation via the VM’s IDataErrorInfo implementation. All controls bound to VM properties that can be “focusable” use the FocusBinding, instead of a normal Binding. When the VM raises its MoveFocus event, the control whose FocusBinding’s Path references the ‘focused property’ will be given input focus.
You can download the source code here. NOTE: Rename the file extension from .DOC to .ZIP and then decompress it. Feedback is welcome!

Every once in a while I post a recording of myself playing a piano piece that I’ve been practicing. This time I’m performing the Allegro from Handel’s second keyboard suite. The recording quality is not ideal, since I never invested in real recording equipment and software. For those of you who like Baroque keyboard music, I hope you enjoy it!
Handel Keyboard Suite 2 – Allegro

A few days ago I received a comment from someone named Joe on my blog. He was expressing concern over several aspects of my book Advanced MVVM, including the fact that it is written about a relatively simple game, not something more complicated. After Joe read the book his apprehensions about it disappeared, and he kindly left me this comment:
Josh,
Ok, after reading your book, I have to say “Wow!” Not only have you managed to help me understand some of the frustrations I had with MVVM development, but your book also made some good points (which I shared with my development manager) and reinforced with real examples of issues I faced working on a project using that pattern.
I was very (pleasantly) surprised reading your take on the code-behind vs. NO code-behind mentality. I myself prefer the middle ground, but for some time was forced to do the latter. Yes, it did create several layers of very difficult to follow, understand and maintain code; from your notes and my examples, I was able to reach a compromise on how we should utilize ‘code-behind’.
Now, an interesting story –our architect chose the MVVM pattern after reading your article in MSDN in 2009. However, they chose to enforce “no code-behind” at all for the sake of testability.
The book is awesome; if you can mix MVVM with Prism and come up with a nice 300+ page book with some nice distilled information like that, I’d a) like to help write it; and b) shell out at least $50.00.
Cheers!
Joe
P.S. you’re right, there is no “Silver Bullet”; however, it would be nice to have some guide or set of documentation as to what works well when and where, especially when certain design patterns are applied to solve a problem.
It sounds like Advanced MVVM has another happy customer!

I’m thrilled to announce that Tim Heuer, one of the top Silverlight community members, evangelists, and Program Managers at Microsoft, has published a review of my book Advanced MVVM. He gave the book a very solid thumbs-up, which made my day! If you’re interested in reading what Tim had to say, here’s the link: http://timheuer.com/blog/archive/2010/03/04/advanced-mvvm-book-for-silverlight-wpf.aspx
Thanks Tim!

I finally found a way to reproduce a minor issue in BubbleBurst, the application reviewed in my Advanced MVVM book. I fixed the issue, which had to do with bursting a bubble group during an animated undo transition, and updated the source code and download files on CodePlex. If you’re interested in seeing the fix, it’s associated with changeset 43211.
By the way, I would like to thank all of you who have bought Advanced MVVM. I am shocked at how many copies have sold so far. This far exceeds my expectations!

Due to popular demand, I have made my Advanced MVVM book available for Amazon’s Kindle e-book reader. You can get it here:
http://www.amazon.com/Advanced-MVVM-ebook/dp/B0038KX9FW
Enjoy!

I have had quite a few people say that they want to print my Advanced MVVM e-book. The DRM protected PDF that you get when you buy the e-book does not allow itself to be printed, as per the rules of Lulu (the online publisher). So, to help people read the book in the format that they want, I made it possible to buy a hard copy of the book. You can get the paperback version here.
I am also in the process of making Advanced MVVM available for the Kindle e-reader. I will blog about it once Amazon approves my book and makes it available online.

I have been working tirelessly for weeks on what I consider to be my masterpiece. I’ve published a book called Advanced MVVM. It is a 52 page deep dive into some complex problems and solutions in an MVVM application I wrote, called BubbleBurst.
You can buy a hard copy, or a digital copy which can be read in the free Adobe Digital Editions e-book reader. It is also possible to read the book on your Amazon Kindle, by purchasing it here.
The full source code is available on CodePlex: http://bubbleburst.codeplex.com/
The e-book’s Table of Contents is shown below:
- The Demo Application
- The Source Code
- WPF
- Learn More about WPF
- MVVM
- Learn More about MVVM
- BubbleBurstView
- BubbleMatrixView
- BubbleCanvas
- BubbleView
- GameOverView
- What Should a View Do?
- Core ViewModel Classes
- BubbleBurstViewModel
- BubbleMatrixViewModel
- Creating Bubbles with BubbleFactory
- Finding Bubble Groups
- A ViewModel is a Model of a View
- What is an Animated Transition?
- Designing for Animated Transitions
- Animated Transitions in BubbleBurst
- Creating Animated Transitions in the ViewModel
- Displaying Animated Transitions in the View
- Responding to User Input
- Creating Undo Tasks
- Managing Bubble Locations
- Benefits of a Task-based Architecture
- Opening the GameOver Dialog
- Closing the GameOver Dialog
- Recap
If you are interested in learning more about my e-book, please click here.
Enjoy!

My good friend and comrade in crime, Karl Shifflett, recently published a huge body of excellent work. He has been working for quite some time on Ocean, a code generation system that blows my mind, and BBQ Shack, a great line-of-business WPF and Silverlight application that is built by Ocean. His prolonged effort has resulted in some high-quality software and documentation (including videos!).
I highly suggest you set aside some time to check out what Karl has been up to. It’s amazing work.
My hat is off to you, Karl!

A recent post by Josh Twist shows how to support mingling code in XAML for WPF devs. There have been several examples of putting code into XAML over the years, and they always raise the discussion of whether or not it is a good practice. I am usually against having code in XAML because it makes it difficult to debug and maintain, but to each his/her own. Regardless, that post got me thinking…
For a while now I’ve wondered how one might go about making it so that the little bits of code in the XAML might somehow be transplanted into the highly testable, debuggable, lovable world of the ViewModel. Sure, you could put this type of logic into value converters, but writing a value converter that is only used once seems like a lot of extra work for little benefit.
Just for kicks, I decided to implement a class that would allow you to specify a method on your ViewModel object that contains the code that would otherwise be placed into a value converter, or in XAML. The result is a markup extension I ever so lazily named BindingEx. Here’s a simple usage:

Notice the last bit where the ConvertMethod property is set to AdjustTextWidth. This is how you specify which method on the element’s VM should be invoked when the window’s width changes. Here’s the VM class:

The TextViewModel object halves the window’s ActualWidth, and that value ends up being the width of the TextBlock.
I’m not sure that anyone should ever use this technique in a real application. It’s probably a very stupid idea altogether, so I want to avoid any bad karma by stressing the point here: USE AT YOUR OWN RISK!!
If you want to check out how I implemented BindingEx, click here to download the source code. Be sure to change the file extension from .DOC to .ZIP and then decompress it.

I recently needed to write some design-time support for a Silverlight framework. I needed to discover a solution’s assemblies while running in Blend, and then pass those assemblies downstream for further processing. In WPF, using the full .NET framework, that’s easy: just call AppDomain.CurrrentDomain.GetAssemblies() and then filter them based on the Location property. In Silverlight, however, a couple of problems showed up that seemed to make this task impossible.
First, the Assembly.Location property is marked ‘Security Critical’ in Silverlight 3. This means that if you access the property, an exception will be thrown.
Second, Silverlight 3’s AppDomain class does not have a GetAssemblies method!
It turns out that both of these problems are easy to overcome. The key thing to know is that when Silverlight code is running in Blend, it’s actually executing against the regular .NET Framework (the same one that WPF uses). You can access ‘Security Critical’ members and no errors occur. That takes care of the Assembly.Location issue. Even though the Silverlight code you write, that is intended to run in Blend, can only access the Silverlight API, you can still access the full .NET framework’s API via reflection. This allows you to work around the second issue. For example:
var assemblies = typeof(AppDomain)
.GetMethod("GetAssemblies")
.Invoke(AppDomain.CurrentDomain, null);
Remember, this hack only works when your Silverlight code is running in Blend! This will not work when running under normal circumstances, since Silverlight apps normally only have access to the Silverlight subset of the .NET Framework.
Happy coding!

I recently published an article on CodeProject that reviews a WPF graphing application. It turns out that my original circular dependency detection algorithm did not detect all circles in certain scenarios. I completely rewrote that algorithm, so that it now properly detects all circles in any object graph.
I also modified the way that the node connectors move, so that it feels more responsive and elastic. The app is much better now, and the article has been updated to reflect these changes (including a new source code download). If you want to check it out, here’s the link:
http://www.codeproject.com/KB/WPF/WpfGraphVisualization.aspx

I spent the weekend having a blast writing a WPF app that displays an interactive object graph, and detects/highlights circular dependencies. It was so much fun, that I decided to publish an article about it on CodeProject.
Here’s a screenshot of the app:
The app uses Charles Petzold’s ArrowLine element, PropertyObserver and ObservableObject from my MVVM Foundation library, DragCanvas from WPF.JoshSmith, and ContentControl3D from Thriple.
If you want to check it out, here’s the article:
http://www.codeproject.com/KB/WPF/WpfGraphVisualization.aspx
Enjoy!

When working on large WPF or Silverlight applications, you can end up with a lot of XAML files. If you are using the MVVM pattern, many of those XAML files contain a View whose DataContext is expected to be set to a certain type of ViewModel object. It can sometimes become difficult to remember which Views expects which ViewModel as their DataContext. One very simple and lightweight way to help you and your team remember a View’s expected DataContext type is to leave an XML comment at the top of the XAML file. This incredibly simple and obvious technique can be a HUGE timesaver later on down the road!

I highly suggest that you get into the habit of doing this, if you haven’t done so already. You will thank yourself many times later…

This morning I decided to build a little WPF dialog window that would show the visual tree of some UI, and provide visual indicators over that UI when you select one of its elements. This was just a fun exercise. If you want to have a serious element tree viewer, then be sure to use Snoop instead. This quick post just shows the result of my morning fun.
Here’s the resulting dialog window in action:
Notice that a ContentPresenter is selected, which contains an image of a ninja. In the UI being analyzed, you’ll see that the ContentPresenter is decorated with a light green box:
The “Snooper” dialog window contains a TreeView that renders the visual tree of the other UI. That TreeView is declared as:
It is bound to a hierarchy of VisualElement objects. VisualElement is a class that I made to represent an element and its child elements. The important part of that class is seen below:
Notice that when a VisualElement is selected, it puts a SelectionAdorner into the adorner layer of its associated UIElement. SelectionAdorner is a class I made that just renders a rectangle around some element. It is seen below:
You can download the demo project here. NOTE: Be sure to change the file extension from .DOC to .ZIP and then decompress. WPF is fun!

I just published an article about a technique I use to streamline and simplify the way that ViewModels are created in an MVVM app. I’m not saying that this is the “right” way to do things, but simply something I find useful. Enjoy!
http://www.codeproject.com/KB/WPF/FromRussiaWithLove.aspx

In case you ever need to prevent the user from selecting a tab in a WPF TabControl, here’s one way to do it…
The SelectedContent of the TabControl hasn’t changed at the time that the ItemsSource’s default collection view raises its CurrentChanging event. If you decide to lock the user into the selected tab, simply set the TabControl’s SelectedIndex back to the index of the SelectedContent. No fuss, no muss…

I set aside some time today to add some goodness, and remove some badness, from my MVVM Foundation library on CodePlex. Special thanks go to Matt Heffron for his great work on making the Messenger class much safer and user-friendly. Here is a listing of the changes:
- Added safety checks and helpful error messages in Messenger for callback registration and message broadcasting. Unit tests were added to verify this behavior.
- Ensured that Messenger notifies colleagues of a message in the order they registered for that message. Unit tests were added to verify this behavior.
- Fixed an issue in an ObservableObject unit test where it failed in a Release build.
It’s exciting for me to see the improvements and ideas suggested by people using MVVM Foundation! I appreciate the time people have contributed toward making the library better. I hope there are no hard feelings when I reject a proposed feature. :)
You can get the latest source code here: http://mvvmfoundation.codeplex.com/SourceControl/ListDownloadableCommits.aspx

I just added a demo application to the MVVM Foundation project on CodePlex. It is contrived, but shows how to use ViewModelBase, RelayCommand, PropertyObserver, and Messenger. You can download the latest source code here.

















