Dynamically Bind XML to DataGrid in Silverlight

后端 未结 2 1118
无人及你
无人及你 2021-01-13 16:21

I\'ve been trying to bind XML (via an XElement) to a DataGrid dynamically in Silverlight (specifically Silverlight 4, but any solutions in SL3 would be fine too) but have be

2条回答
  •  说谎
    说谎 (楼主)
    2021-01-13 16:37

    Below is another alternative that may also help. It's a bit of a hack.

    It's written and tested using Silverlight 3.

    The ViewModel:

    namespace DatagridXml
    {
        public class TestViewModel
        {
            public TestViewModel()
            {
                XmlData = @"Name121
    Address1
    Name222
    Address2
    Name323
    Address3
    "; } public string XmlData { get; set; } } }

    The value converter:

    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.Linq;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Xml.Linq;
    
    namespace DatagridXml
    {
        public class XmlColumnConverter : IValueConverter
        {
            public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            {
                string elementToGenerate = parameter.ToString();
                DataGrid control = value as DataGrid;
                control.Columns.Clear();
    
                var result = new List>();
                XDocument xmlDoc = XDocument.Parse(control.DataContext.ToString());
    
                // Generate Columns
                var columnNames = xmlDoc.Descendants(elementToGenerate).FirstOrDefault();
                int pos = 0;
                foreach (var columnName in columnNames.Elements())
                {
                    var column = new DataGridTextColumn();
                    column.Header = columnName.Name;
                    column.Binding = new Binding("[" + pos + "]");
                    control.Columns.Add(column);
                    pos++;
                }
    
                // Parse elements to generate column's data
                foreach (var element in xmlDoc.Descendants(elementToGenerate))
                {
                    var row = new List();
                    foreach (var column in element.Elements())
                    {
                        row.Add(column.Value);
                    }
                    result.Add(row);
                }
                return result;
            }
    
            public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
            {
                throw new NotSupportedException("Cannot convert to xml from list.");
            }
        }
    }
    

    And, you use like this:

    
        
            
            
        
        
            
        
    
    

提交回复
热议问题