问题
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?
回答1:
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
来源:https://stackoverflow.com/questions/1065942/are-wpf-binding-properties-path-and-xpath-mutually-exclusive