将Silverlight Datagrid绑定到Excel XML文件夹

时间:2010-07-13 18:31:09

标签: xml silverlight excel datagrid observablecollection

我正在尝试从已保存为XML的Excel文件中提取数据并将其绑定到Silverlight DataGrid。我正在按照我在网上找到的教程,但我无法获得理想的结果。

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Xml.Linq;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using System.Windows.Data;
using System.Collections.ObjectModel;

namespace AmicusToApexImporter
{
    public partial class MainPage : UserControl
    {

        static ObservableCollection<List<string>> items = new ObservableCollection<List<string>>();

        public MainPage()
        {
            // Required to initialize variables
            InitializeComponent();
        }

        private void ImportXMLFIle()
        {

            var doc = XDocument.Parse(ReadUserXMLFile());

            PopulateExcelDataToDataGrid(doc);

            SetupDataGridFromSpreadsheetColumnNames(doc);

        }

        private string ReadUserXMLFile()
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Multiselect = false;
            dlg.Filter = "Excel XML Files (*.xml)|*.xml";
            bool bResult = (bool)dlg.ShowDialog();
            if (!bResult)
                return "";

            FileInfo info = dlg.File;
            StatusText.Text = info.Name;

            // open the stream for reading

            Stream s = info.OpenRead();

            StreamReader reader = new StreamReader(s);

            var xml = reader.ReadToEnd();
            return xml;
        }

        private void SetupDataGridFromSpreadsheetColumnNames(XDocument doc)
        {
            // get a list of column names
            var columnNames = doc.Descendants().Where(x => x.Name.LocalName == "Row").First().Descendants().Where(y => y.Name.LocalName == "Data").Select(q => q.Value).ToList();

            int count = 0;
            // create the columns in the datagrid and set the bindings to use
            // a value converter that can process the array of strings
            foreach (var name in columnNames)
            {
                var column = new DataGridTextColumn() { Header = name };
                dataGrid1.Columns.Add(column);
                column.Binding = new Binding() { Converter = (IValueConverter)this.Resources["arrayIndexToValueConverter"], ConverterParameter = count };
                count++;
            }
            // set the data source of the data grid
            dataGrid1.ItemsSource = items;
        }

        private static void PopulateExcelDataToDataGrid(XDocument doc)
        {
            var rows = doc.Descendants().Where(x => x.Name.LocalName == "Row");

            int rowCount = 0;
            foreach (var row in rows)
            {
                // skip the data in the first row since it is the header
                if (rowCount > 0)
                {
                    var data = row.Descendants().Where(y => y.Name.LocalName == "Data").Select(q => q.Value).ToList();
                    items.Add(data);
                }

                rowCount++;
            }
        }

        private void btnGo_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            ImportXMLFIle();
        }


    }

    public class ArrayIndexToValueConverter : IValueConverter
    {

        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            var index = (int)parameter;
            var list = value as List<string>;
            if (index >= list.Count) return "";
            return list[index];
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion
    }

}

Datagrid中的所有字段都填充了“system.collections.generic.list 1 system.string”,另外三个添加列添加到网格 - 容量,计数,项目。

我做错了什么?感谢。

2 个答案:

答案 0 :(得分:1)

看看以下接受的答案:

Dynamically Bind XML to DataGrid in Silverlight

它需要采用不同的方法,但我相信它也会起作用。

答案 1 :(得分:0)

我知道这篇文章太旧了,我问google答案,但对我没什么用。

解决方案是:

首先,在xaml页面中声明您在代码中实现的IValueConverter类,例如:

.... 的xmlns:MC = “http://schemas.openxmlformats.org/markup-compatibility/2006” XMLNS:地方= “CLR的命名空间:SilverLigthApp” ....

然后哟必须有一个资源,代码正在寻找一个名为“arrayIndexToValueConverter”的资源,在“column.Binding = new Binding(){Converter =(IValueConverter)this.Resources [”arrayIndexToValueConverter“],ConverterParameter = count};“

因此,您必须在控制资源部分声明:

  

....

试试这个,它对我有用。

对不起我的英语,我希望这对你有用,就像它为我做的那样。

相关问题