在代码中加载XmlDataProvider

本文关键字:XmlDataProvider 加载 代码 | 更新日期: 2023-09-27 18:21:14

我对感到困惑

我有xml文档

<?xml version="1.0" encoding="utf-8"?>
<Reports>
  <Report Id="AAAAA-ABBB">
    <DocId>10110001</DocId>
    <DocName>ESP North Casing</DocName>
    <DocType>2010-01-01</DocType>
    <Status>1</Status>
    <CreatedById>1</CreatedById>
    <SiteId>1</SiteId>
    <Language>1</Language>
    <Updated>2011-01-01</Updated>
    <Published>2011-01-01</Published>
    <FilePath>c:''reports'20011001.docx</FilePath>
  </Report>
  <Report Id="AAAAA-ABBC">
    <DocId>10110002</DocId>
    <DocName>ESP South Casing</DocName>
    <DocType>2010-01-01</DocType>
    <Status>1</Status>
    <CreatedById>1</CreatedById>
    <SiteId>1</SiteId>
    <Language>1</Language>
    <Updated>2011-01-01</Updated>
    <Published>2011-01-01</Published>
    <FilePath>c:''reports'20011001.docx</FilePath>
  </Report>
</Reports>

如果我定义一个静态xmldataprovider,比如

 <UserControl.Resources>
    <XmlDataProvider x:Key="ReportData"
               Source="../DesignData/report.xml"
               XPath="Reports/Report" />
    <DataTemplate x:Key="teamItemTemplate">
        <Label Content="{Binding XPath=DocId}"/>
    </DataTemplate>
</UserControl.Resources>

并在列表框中显示文档

<ListBox x:Name="ReportListBox" Margin="60,12,114,64" DockPanel.Dock="Left"
             ItemsSource="{Binding 
         Source={StaticResource ReportData}}"
             ItemTemplate="{StaticResource teamItemTemplate}"
             IsSynchronizedWithCurrentItem="True"
             Visibility="Visible" SelectionMode="Single">
</ListBox>

我可以在列表框中看到数据

如果我在代码中也这样做,并在我的视图模型中加载xmldataprovider

  private XmlDataProvider GetXMLReports()
        {
              string filePath = Directory.GetCurrentDirectory() + @"'Data'report.xml";
              XmlDataProvider provider = new XmlDataProvider(); 
                System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); 
              doc.Load(filePath); 
              provider.Document = doc; 
              provider.XPath = "Reports/Report";
              //Reports = _provider;
              return provider;
        }
        public XmlDataProvider Reports
        {
            get { return _provider; }
            set
            {
                _provider = value;
                this.RaisePropertyChanged(() => this.Reports);
            }
        }

如果我将datacontext设置为viewmodel并绑定到属性Report

<ListBox x:Name="ReportListBox" Margin="60,12,114,64" DockPanel.Dock="Left"
                 ItemsSource="{Binding Path=Reports}"
                 ItemTemplate="{StaticResource teamItemTemplate}"
                 IsSynchronizedWithCurrentItem="True"
                 Visibility="Visible" SelectionMode="Single">
    </ListBox>

什么都没有显示,任何想法。

在代码中加载XmlDataProvider

您想要实现的目标是不可能实现的。

作为一种变通方法,您可以像这样在ListBox中设置DataContext,它应该可以工作:

     DataContext="{Binding Reports}"    
     ItemsSource="{Binding}"