How to bind XmlDataProvider.Source to MVVM property

血红的双手。 提交于 2019-11-28 13:00:57

The answer appears to be: you can't.

I was able to solve my underlying problem (binding a treeview to an Xml document) by removing the XmlDataProvider from the equation and binding the TreeView directly to a ViewModel property that returns an XmlNode.

What had been tripping me up was that I took the binding code that pointed at the XmlDataProvider and pointed it at my property, leaving the XPath argument in place.

<TreeView ItemsSource="{Binding Path=ProjectDocument XPath=.}">

This would result in a runtime error: System.Windows.Data Error: 44 : BindingExpression with XPath cannot bind to non-XML object.; XPath='.'

Which was not the most helpful. What it was really trying to say is that you can't bind to an XmlNode property AND provide an XPath argument in the binding (because it's the XmlDataProvider that knows what to do with that??).

<TreeView ItemsSource="{Binding Path=ProjectDocument}">

actually that was rather tough problem for me, cause I needed the app to load treeview from temp file, and assuming application can have different locations, I can't set strict link in the XmlDataProvider Source property;

Add source as resource to the project

the solution I found is adding temp file (markup is created via XAML, see below) to the project with build action set to Content thus, application reloads it every time you call InitializeComponent() on the object containing XmlDataProvider and my treeview updates.

    <XmlDataProvider x:Key="dshPreview" 
                     Source="~tmpConstruct.xml" 
                     XmlNamespaceManager="{StaticResource argNms}"   
                     IsAsynchronous="true"/>

TreeView is bound like this:

  <TreeView  x:Name="PreviewTree" 
             ItemsSource="{Binding Source={StaticResource dshPreview},
             XPath=/mns:engine/mns:ws}"
              />         

Maybe this will help someone

I didn't find how to bind the source straight away, but you can change the XmlDataProvider source in the code behind as following:

var xdp = (XmlDataProvider)this.Resources["key-of-your-XmlDataProvider-in-resources"];
xdp.Source = new Uri("http://url-of-your-xml");

You can use that combined with an event handler to bind.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!