WPF Binding and Resource Lookup Complexities

I am working on a project that builds a lot of the visual structure using code.  I am attempting to leverage XAML to layout the visuals, and use my code to” pull together” the visual elements in response to user choices. In addition, I am seeking to do this by actually assigning ViewModel objects to ViewModel properties to which a ContentControl has been previously bound, with the expectation that the framework can look-up the DataTemplate for the ViewModel object and apply the visuals.

In this example VS2010 project, I am seeking to add a TabControl to a Grid using a command.  When a Red border appears inside the Blue border, the command is working.  In the example project, the NewTabControlCommand does not work and NewTabControlViaContentControlCommand does work.  Note, for simplicity of this example, the NewTabControlViaContentControlCommand approach violates some MVVM principles as shown, but could be made to be a good MVVM citizen by use of a ViewService.  I have a blog entry here from a presentation that I gave about how and when to use a ViewService.

The complexity of seeking to “feed” the WPF framework a DataType and expecting it to look-up the visuals comes from the fact that not all properties provide the same behavior.

Lets use this TabControl ItemsControl as an example:

<TabControl
            IsSynchronizedWithCurrentItem=”True”
            SelectedItem=”{Binding SelectedTabItem}”
            ItemsSource=”{Binding TabItemViewModels}”
            ContentTemplate=”{StaticResource tabContentDataTemplate2}”
            x:Name=”tabControl1″
            FontSize=”20″
            BorderBrush=”Red”
            BorderThickness=”5″ />

The ItemsSource property will happily retrieve the ObservableCollection<TabItemViewModel> from the TabItemViewModels property, it will see that they are not a Visual type, and proceed to look-up the visuals in the Resource tree.  It will then render the visuals, add them to the tree, and use the TabItemViewModel as the DataContext.  The looked-up DataTemplate wil be used to draw the visual content of the tab use by the user to select the TabItem.  Very good.

However, the ContentTemplate must receive a DataTemplate.  Even if you provide a ViewModel type which could be resolved to a DataTemplate in the Resource tree, it will not work.  Moreover, ContentTemplate on the TabControl does not use the TabControl’s DataContext.  Rather, it too will receive the DataContext of each TabItem given by ItemSource, and therefore, any bindings in your DataTemplate needs to expect that the DataContext will be a TabItem, not a TabControl.

Also, I talk more about this in a lengthy post on StackOverflow, but I want to at least  mention it here as well.  It is invalid to set a DataContext directly to a ViewModel.  Similar to the ContentTemplate example above, this will not lookup the visuals in the Resource tree and give you the visuals with the ViewModel as the DataContext.  It would be nice if at least  the <ContentControl> and <ItemsControl> offered this type behavior, but they do not.

Lastly, it is important to note that your Bindings must resolve when you initiate the control.  You can change the values later, which is of course the point of setting up the Binding, but the Binding must resolve upon initiation.  For example, I was seeking to point some CommandParameters at binding targets that I knew would exist (after being created by code) when the user clicked the button that triggered the Command, but which would not exist when the Button providing the Command was initiated.  The CommandParameter did not detect that the binding contained a valid value at “click-time” – presumably because it failed to ever get established.  I believe this is true for both looking up an element that does not exist by using the ElementName binding in XAML, as well as if you bind to a property in the DataContext that returns null upon the initial binding.  Subsequently setting the property – even if you implement INotifyPropertyChange – will not establish/refresh the binding.

.Net Delegates and Events Resources

The following resources are the most thorough I found on events and delegates in .Net.; great treatments for both learning and reference.

C# Event Implementation Fundamentals, Best Practices and Conventions – As good as it gets, this article is well organized, contains a Table of Contents, defines all terms and gives a thorough treatment to events and delegates in .Net.

Understanding .NET Delegates and Events, By Practice – A very good treatment of delegates.

Func and Action Generic Delegates – Concise examples and descriptions of the use of generic delegates.

 

C# Event Implementation Fundamentals, Best Practices and Conventions

User Interactions in MVVM: Commands and Events and Behaviors – Oh My!

It took me a while to get the Zen of Commanding versus traditional Event handling in WPF / Silverlight / WinRT programming.  After much thought and some experimenting with which mechanism I wanted to structure my user interactions around, I settled on a Commanding as a first approach.

Let me first say that the article MVVM Made Simple gave me much to think about with respect the notion “Why not leverage the .NET event model when using the MVVM design pattern, and avoid Commanding?”  The bottom line is, while I think the approach used in the above article has much merit, I think that it would break down in more complex scenarios, when more contextual information may be required.  You could always create an event-to-command pattern for such situations, but the bottom line is that the Commanding constraints would ultimately need to be adhered to in some form in order to maintain the separation of UI concerns and ViewModel concerns required by the goals and principles of the MVVM pattern.  As such, where events are the only mechanism available to act on an interaction, the approach described by the article is perfectly consistent with the MVVM pattern;  I just don’t think it should be the first choice for modeling the underlying code where Commanding is available.

Commanding is the model of choice, and where needed, an Event-to-Command adapter can be employed.  The Event-to-Command adapter would be a View component, and would pre-process the sender and event arguments such that only values that could be reproduced using a test harness (UI elements and events are notoriously difficult or impossible to simulate using automated tests) are passed into the Command object methods.  This preserves another of the key goals of MVVM, which is to allow application logic and code to be tested using automated testing techniques.

One of the more obvious benefits of Commanding is that it can be used declaratively in XAML.  Another benefit is that when a ViewModel that implements ICommand backs a UserControl or DataTemplate UI element with a 1) Command and 2) CommandParameter set to the DataContext of the UI element, the Command gains access to the DataContext (ie, ViewModel) of the UI element in which it is defined.  This is handy for accessing values of other elements in the UserControl or DataTemplate which may be used to parameterize the Command.

Finally, a discussion of handling user interactions would not be complete without a mention of Behaviors.  In his article, Introduction to Attached Behaviors in WPF, Josh Smith summarizes an Attached Behavior – or just, Behavior – as follows: “The idea is that you set an attached property on an element so that you can gain access to the element from the class that exposes the attached property. Once that class has access to the element, it can hook events on it and, in response to those events firing, make the element do things that it normally would not do. It is a very convenient alternative to creating and using subclasses, and is very XAML-friendly.”  You can take a look at Josh’s discussion of Attached Behaviors in his excellent article to learn more about the underlying technique, and also Laurent Bugnion’s excellent implementation of a “Magnify” Behavior to see a powerful example.


Learning MVVM – Introducing A “Series” of Posts

Learning the Model-View-ViewModel (MVVM) pattern over the past year has been a very interesting, but also very challenging experience.  In my case, it required learning several new concepts and devices that enable the Windows Presentation Foundation (WPF) technologies first.  So, for me, learning MVVM – really the only proper way to develop a WPF application that will have any significant lifespan – was on the heels of a “heavy lift” learning WPF.  And, of course, I am still learning about both areas, but I believe I have reached a functional level of competence in both, and wanted to capture and share at least some of the resources that I have found valuable along the way – and to which I have returned again and again.

In this post, I will list those that are on the top of my mind, but I will be tagging follow-up posts in this series with the “learning-mvvm” and “learning-wpf” tags.  Other posts which may be instructive to problems I needed to solve related to MVVM or WPF will only be tagged “mvvm” or “wpf”.

Okay, so here is the initial list:

WPF Tutorial – great site for introduction to WPF fundamentals

Dr. WPF – great site with a great series on items controls

Adam Nathan’s WPF 4 Unleashed (2010) – I think a lot of people like this treatment of WPF; very valuable reference;  I read my copy on O’Reilly’s Safari service, but it is also available for Amazon’s Kindle

Josh Smith’s MVVM Demo app and article – excellent article to see how something useful can be done in MVVM

Laurent Bugnion’s MVVMLight Framework – framework that provides some reusable code that would otherwise need to be written by you;  light enough, transparent enough, and powerful enough to be leveraged in wide range of scenarios

Laurent Bugnion’s MIX 10 (Introduction to MVVM) and MIX 11 (MVVM Deep Dive) video presentations;  worth watching – several times – and in order;  only move on to the “Deep Dive” video after the “Introduction” topics are fairly well understood

Karl Shifflett’s Ocean Framework and BBQ Shack application – Visual Basic application and framework; I program in C#, so I have not returned to look at Karl’s stuff too often, but some very interesting stuff going on with the UI in the BBQ Shack app; definitely worth a look at the videos showing the UI features to see what is really possible; I have only watched the WPF video so far, but I will likely go back and checkout the “Non-linear Navigation Deep Dive” at some point

Well, I think that is a good initial post for this “series.”  Other posts will follow, and be tagged as described above, as other materials come to mind, or when I think a given piece of learning was particularly hard-won, or is otherwise worth emphasizing.

Why and How to Use a ViewService in MVVM

(Originally presented at the Long Island .NET Users’ Group)

I really enjoyed the holiday social. Good to see everyone. I enjoyed presenting “Why and How to Use a ViewService in MVVM.” If you were able to attend, or have just downloaded the materials, I always appreciate feedback and enjoy discussion on technical topics, so please don’t hesitate to contact me.

Here are the slides:  Why and How to Use a ViewService in MVVM

Here is the code for the Demo:  DialogService ViewService Demo Code

Update: 12/19/2011 —  Just found this blog post by Laurent Bugnion where he talks about using a ViewService for navigation.  I think the ViewService strategy originates with Laurent, and I know that that is where I learned about it – originally in Laurent’s MIX 11 talk.