简体   繁体   中英

Set XMLDataProvider source dynamically

While all examples and sources I found is to set the resource in XAML statically, I would only know in run time the name of the XML file to be connected with XMLDataProvider. Is there a way to set either in code behind or in XAML?

<Window.Resources>
    <XmlDataProvider x:Key="XMLFoo" Source="Foo.xml" XPath="Foo"/>
</Window.Resources>

It could be Foo.xml, or could be Goo.xml.

Yes you can change that while runtime. Unfortunately you cannot bind it, so you have to do stuff in Code-Behind.

Here's a simple example:

(this.Resources["XMLFoo"] as XmlDataProvider).Source = new Uri("Goo.xml");

Cheers

If you are trying to have just one instance of XamlDataProvider and would like your source to change dynamically, I don't think it is possible in pure XAML as you cannot bind to Source property, since that is not a DependencyProperty .

From code-behind, you can get the instance your provider and change it's source.

var provider = (XmlDataProvider) Resources.FindName("XMLFoo");
provider.Source = new Uri("bar.xml", UriKind.Relative);

Alternatively, you can use MVVM and expose your XmlDataProvider as a property on the ViewModel and bind it to your View, you can then change the Source and refresh data from the ViewModel itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM