Are WPF binding properties Path and XPath mutually exclusive?

sourcenouveau picture sourcenouveau · Jun 30, 2009 · Viewed 7.7k times · Source

Suppose I have a UserControl whose DataContext is set to an object that has an XmlDataProvider property. I would like to bind to this property in my control's XAML, and specify some XPath. I tried this:

<TreeView ItemsSource="{Binding Path=PropertyName, XPath=/items/item/*}">

At runtime I get the exception "BindingExpression with XPath cannot bind to non-XML object". Removing the Path property and setting the TreeView's DataContext to the XmlPropertyName directly works fine.

What gives? Are Path and XPath mutually exclusive?

Answer

rmoore picture rmoore · Jul 1, 2009

They are not mutually exclusive, as briefly mentioned in the Data Binding Overview under the Specifying the Path to the Value section. The XPath expression will be executed before the Path property, but is sometimes desirable to use as Bea Stollnitz explains here and here.

"Removing the Path property and setting the TreeView's DataContext to the XmlPropertyName directly works fine."

Since you mentioned this, it seems to me like you are expecting the Path property to be evaluated before the XPath expression, which would be why you are getting an error, the XPath expression is evaluating on whatever your current context is, and the path is being evaluated after that. error explanation