开发者

Need help hooking up XML file to WPF DataGrid

Here's what I've done so far:

  1. In my App class, I declare a new XmlDataProvider and set the source to a valid XML file (whose Build Action is set to Content/Copy Always).

    public partial class App : Application
    {
        public App()
        {
            InitializeComponent();
            var services = new XmlDataProvider();
            services.Source = new Uri("pack://siteoforigin:,,,/Data/Services.xml"); // also tried an absolute path, but that made no difference
            var mainWindow = new MainWindow();
            mainWindow.DataContext = new MainViewModel(services);
            mainWindow.Show();
        }
    }
    
  2. The XmlDataProvider gets passed into the ViewModel and gets assigned to the Services property.

  3. I bind to the data like this:

    <mwc:DataGrid
        ItemsSource="{Binding Services, XPath=//Services/*}">
        <mwc:DataGrid.Columns>
            <mwc:DataGridTextColumn
                Binding="{Binding XPath=@name}"
                Header="Name" />
            <mwc:DataGridTextColumn ... />
            ...
        </mwc:DataGrid.Columns>
    </mwc:DataGrid>
    

The result:

The column headings of my DataGrid show up, but there are no rows of data. It compiles and runs without any errors, but if I check my Output window, I see this:

BindingExpression with XPath cannot bind to non-XML object.;
XPath='//Services/开发者_运维问答*'
BindingExpression:Path=Services;

Can the XmlDataProvider only be used declaratively?

If I attempt to create the XmlDataProvider declaratively in a ResourceDictionary like this...

<XmlDataProvider
    x:Key="Main_Services">
    <x:XData>
        <Services
            xmlns="">
            <Service
                name="Test"
                ... />
            <Service ... />
            ...
        </Services>
    </x:XData>
</XmlDataProvider>

...everything works fine (I get the expected rows in my DataGrid). (Note that I just pasted the contents of the XML file between the <x:XData> tags.)

If I try to set the Source via C#, however, there doesn't seem to be any data in the XmlDataProvider (literally, the Data property is null).

It doesn't seem to make any difference whether I use a "pack URI" or an absolute path when I assign the Source. I get no rows either way. I also tried calling the InitialLoad() method after setting the source, but that made no difference either.

Questions:

  • Is XmlDataProvider just the wrong tool for the job or am I doing something wrong?
  • Can XmlDataProvider only be used declaratively?
  • I know there is XDocument and XmlDocument...should I be using one of those?


Declarative seems to be the way to go. This code works:

<XmlDataProvider
    x:Key="Main_Services"
    Source="pack://siteoforigin:,,,/Data/Services.xml">
</XmlDataProvider>

I have no idea why doing the same exact thing in C# fails, but I can live with this solution.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜