The Binding class in WPF has some interesting behavior of which you should be aware.  By default, when it encounters a DataSourceProvider subclass it does some fancy footwork which makes most use cases intuitive, but can throw a monkey wrench into other scenarios.  I am referring specifically to the BindsDirectlyToSource property.  By default that property is false, but sometimes you will need to set it to true.  Here’s an example…

Someone recently posted a question on the WPF Forum which asked how to bind the visibility of a Grid panel to the ObjectInstance property of an ObjectDataProvider.  Basically, he wanted to hide a Grid when the ObjectInstance property was null, and show it when the property was non-null.  The ObjectDataProvider’s ObjectInstance property was set to a non-null value when the user created a new document in his application.  In addition, he wanted to do all of this in XAML. 

It turns out that this is one of the rare scenarios where you actually want to bind against a property of ObjectDataProvider, not the data object it exposes via the Data property.  Here’s a summary of the XAML I created to solve this problem:

Binds Directly To Source

When you run the demo application, it will initially look like this:

ObjectInstance is null

When you uncheck the CheckBox, which gives a value to the ObjectDataProvider’s ObjectInstance property, it will look like this:

Buckwheat is in da house!!!

That’s right Buckwheat, an object exists. 😀

 (Note: This example is not a scenario in which binding directly to the ObjectDataProvider is absolutely necessary.  You could just bind to the provider without setting BindsDirectlyToSource to true or setting the Path to ObjectInstance property, and get the same results.  The point here is that if you want to bind to a property on the data provider, you need to bind directly to the provider itself.)

You can download the source code here: BindsDirectlyToSource demo app  Be sure to change the file’s extension from .DOC to .ZIP and then decompress it.

One Response to BindsDirectlyToSource

  1. […] are patient and knowledgeable. Josh Smith not only answered one of my questions, he subsequently blogged about it with a concrete example. […]

%d bloggers like this: