开发者

Creating a DataTable Inside an IValueConverter Class For DataGrid Binding

I need to create a DataGrid that is bound to an object that is similar to the following:

public class MyClass
{
    public string Header { get; set; }
    public string[] Values { get; set; }
}

As you can see, the headers needed for the table aren't the property names of the object so I can't just use AutoGenerateColumns off the bat. My idea so far is to use a converter to take the MyClass objects and convert them into a DataTable.

public object Convert(
    object value, 
    Type targetType, 
    object parameter, 
    System.Globalization.CultureInfo culture)
{
    var items = value as IEnumerable<MyClass>;
    if (items != null)
    {
        DataTable dTable = new DataTable();
        foreach (MyClass item in items)
            dTable.Columns.Add(new DataColumn(item.Header, typeof(string)));

        return dTable;
    }
    else
        return null;
}

I'm setting the containing grid's DataContext to be a List<MyClass> object and the Convert() method is hit and the DataTable is created OK by the looks of things, but when I come to run the app, the DataGrid is just blank. Here's a basic vie开发者_如何学JAVAw of my XAML:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication1"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <local:DataTableConverter x:Key="converter"/>
    </Window.Resources>

    <Grid x:Name="grid">
        <DataGrid AutoGenerateColumns="True"
                  ItemsSource="{Binding Path=., Converter={StaticResource converter}}"/>
    </Grid>
</Window>

Any ideas why the DataGrid remains empty?


Of course it's blank, you're creating a DataTable without any rows.

If I understand your (slightly odd) design correctly, each MyClass represents one column with all its values. To display that, you have to fill the rows of the DataTable with values from your class:

public object Convert(
    object value, Type targetType, object parameter, CultureInfo culture)
{
    var items = value as IEnumerable<MyClass>;
    if (items != null)
    {
        var array = items.ToArray();
        var dTable = new DataTable();
        foreach (MyClass item in array)
            dTable.Columns.Add(new DataColumn(item.Header, typeof(string)));

        if (array.Length > 0)
            for (int i = 0; i < array[0].Values.Length; i++)
                dTable.Rows.Add(array.Select(mc => mc.Values[i]).ToArray());

        return dTable;
    }
    return null;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜