将 Silverlight Datagrid 绑定到 Excel XML 文件

发布于 2024-09-09 15:52:31 字数 4188 浏览 3 评论 0原文

我正在尝试从已保存为 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
    }

}

数据网格中的所有字段均填充有“system.collections.generic.list 1 system.string”,并且其他三个附加列将添加到网格中 - 容量、计数、项目。

我做错了什么?谢谢。

I am trying to pull the data from an Excel File that has been saved as XML and bind it to a Silverlight DataGrid. I am following a tutorial that I found on the web, but I cannot get the desired results.

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
    }

}

All of the fields in the Datagrid are populated with "system.collections.generic.list 1 system.string" and three other addition Columns are added to the Grid - Capacity, Count, Item.

What am I doing wrong? Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

清引 2024-09-16 15:52:31

我知道这篇文章太旧了,我向谷歌询问了答案,但对我来说没有任何作用。

解决办法是:

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

...
xmlns:mc =“http://schemas.openxmlformats.org/markup-compatibility/2006”
xmlns:local="clr-命名空间:SilverLigthApp"
....

那么你必须有一个资源,代码正在“column.Binding = new Binding() { Converter = (IValueConverter)this.Resources["arrayIndexToValueConverter"], ConverterParameter 行中查找名为“arrayIndexToValueConverter”的资源=计数};”

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

....

试试这个,它对我有用。

抱歉我的英语不好,我希望这对你有用,就像它对我一样。

I know this post is too old, I asked google for the answer but nothing worked for me.

The solution is:

First of all, declare in the xaml page your IValueConverter Class that you have implemented in code, for example:

....
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:SilverLigthApp"
....

then yo must have a resource, the code is looking for a resource called "arrayIndexToValueConverter" in the line "column.Binding = new Binding() { Converter = (IValueConverter)this.Resources["arrayIndexToValueConverter"], ConverterParameter = count };"

So, you must declare in the control resource section:

....

Try this, it worked for me.

Sorry for my English, I hope this work for you as it have done for me.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文