Привязка сетки данных Silverlight к файлу Excel XML - PullRequest
1 голос
/ 13 июля 2010

Я пытаюсь извлечь данные из файла Excel, который был сохранен в формате XML, и связать его с сеткой данных Silverlight. Я следую учебному пособию, которое нашел в Интернете, но не могу получить желаемые результаты.

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", и три других дополнительных столбца добавляются в таблицу - Capacity, Count, Item.

Что я делаю не так? Спасибо.

Ответы [ 2 ]

1 голос
/ 14 июля 2010

Взгляните на следующий принятый ответ:

Динамическое связывание XML с сеткой данных в Silverlight

Это другой подход, но я верю, что он тоже будет работать.

0 голосов
/ 05 декабря 2014

Я знаю, что это сообщение слишком старое, я запросил у Google ответ, но у меня ничего не получилось.

Решение:

Прежде всего, объявите на странице xaml свой IValueConverterКласс, который вы реализовали в коде, например:

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

тогда у вас должен быть ресурс, код ищет ресурс «arrayIndexToValueConverter» в строке «column». Binding = new Binding () {Converter = (IValueConverter) this.Resources ["arrayIndexToValueConverter"], ConverterParameter = count};"

Итак, вы должны объявить в разделе ресурса управления:

....

Попробуйте, это сработало для меня.

Извините за мой английский, я надеюсь, что эта работа для вас так же, как и для меня.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...