在Silverlight中动态地将XML绑定到DataGrid

时间:2010-07-12 17:40:51

标签: xml silverlight data-binding datagrid

我一直在尝试在Silverlight中动态地将XML(通过XElement)绑定到DataGrid(特别是Silverlight 4,但SL3中的任何解决方案都可以。)但是无法这样做。我希望动态地这样做(即 - 没有严格的业务对象来表示XML)。

我最终希望能够绑定到包含任意XML的任何XElement,然后使用某种IConverter将XElement转换为DataGrid可以绑定的内容 - 并且只是“知道”如何从转换后的对象中自动生成列和行。

<sdk:DataGrid 
    ItemsSource="{Binding Source={StaticResource MyViewModel}, 
    Path=MyXElement, Converter={SomeConverter}}" AutoGenerateColumns="True">

如果可能的话,我希望能够利用某种可重用的声明性组件(试图避免实际视图的代码隐藏)。

我尝试过使用DynamicObjects,但DataGrid无法弄清楚它的属性。

2 个答案:

答案 0 :(得分:2)

以下是另一种可能有帮助的替代方案。这有点像黑客。

它是使用Silverlight 3编写和测试的。

ViewModel:

namespace DatagridXml
{
    public class TestViewModel
    {
        public TestViewModel()
        {
            XmlData = @"<people><person><name>Name1</name><age>21</age><address>Address1</address></person><person><name>Name2</name><age>22</age><address>Address2</address></person><person><name>Name3</name><age>23</age><address>Address3</address></person></people>";
        }
        public string XmlData { get; set; }
    }
}

值转化器:

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<IList<string>>();
            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<string>();
                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.");
        }
    }
}

并且,你这样使用:

<UserControl
    x:Class="DatagridXml.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"
    xmlns:local="clr-namespace:DatagridXml"
    mc:Ignorable="d"
    d:DesignWidth="640"
    d:DesignHeight="480">
    <UserControl.Resources>
        <local:XmlColumnConverter
            x:Key="XmlColumnConverter" />
        <local:TestViewModel
            x:Key="TestViewModel" />
    </UserControl.Resources>
    <Grid
        x:Name="LayoutRoot">
        <data:DataGrid
            AutoGenerateColumns="False"
            DataContext="{Binding Source={StaticResource TestViewModel}, Path=XmlData}"
            ItemsSource="{Binding RelativeSource={RelativeSource Self}, Converter={StaticResource XmlColumnConverter}, ConverterParameter=person}" />
    </Grid>
</UserControl>

答案 1 :(得分:0)