Binding directly to a public property of a collection inside ViewModel

You create a WPF window in the application. You add the following code segment to the application.
public class ViewModel
public CollectionView Data { get; set; }
public class BusinessObject
public string Name { get; set; }
The DataContext property of the window is set to an instance of the ViewModel class. The Data property of
the ViewModel instance is initialized with a collection of BusinessObject objects. You add a TextBox control
to the Window. You need to bind the Text property of the TextBox control to the Name property of the
current item of the CollectionView of the DataContext object. You also need to ensure that when a binding
error occurs, the Text property of the TextBox control is set to N/A. Which binding expression should you

A. { Binding Path=Data/Name, FallbackValue=’N/A’ }
B. { Binding Path=Data.Name, FallbackValue=’N/A’ }

I used to think that it’s Data.Name, since we intuitively feel the ‘.’ syntax is the correct way to dig deeper into an object. Actually, that’s not the case in this scenario. The object collection in the view model is not bound first to an items control like combobox. If that was the case, then inside each combo box item you could easily call Name directly and the binding would cascade correctly. Here, we are directly trying to get to second level of object hierarchy and therefore the way to do it is to use XPath style syntax: Data/Name, and this will grab the first item in the collection  and bind its Name property to our textbox’s text. Even, if you add 10 textboxes, all will still grab the first item with this syntax.

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s