简体   繁体   English

动态设置XMLDataProvider源

[英]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. 虽然我发现的所有示例和资源都是在XAML中静态设置资源,但我只会在运行时知道要与XMLDataProvider连接的XML文件的名称。 Is there a way to set either in code behind or in XAML? 有没有办法在代码后面或XAML中进行设置?

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

It could be Foo.xml, or could be Goo.xml. 它可以是Foo.xml,也可以是Goo.xml。

Yes you can change that while runtime. 是的,您可以在运行时更改它。 Unfortunately you cannot bind it, so you have to do stuff in Code-Behind. 不幸的是,您无法绑定它,因此您必须在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 . 如果您尝试仅使用XamlDataProvider一个实例,并且希望您的源动态更改,那么我认为在纯XAML中是不可能的,因为您不能绑定到Source属性,因为这不是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. 或者,您可以使用MVVM并将XmlDataProvider公开为ViewModel的属性,并将其绑定到View,然后可以更改Source并从ViewModel本身刷新数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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