【问题标题】:Creating a DataTable Inside an IValueConverter Class For DataGrid Binding在 IValueConverter 类中为 DataGrid 绑定创建 DataTable
【发布时间】:2011-09-22 21:46:08
【问题描述】:

我需要创建一个绑定到类似于以下对象的 DataGrid:

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

如您所见,表所需的标题不是对象的属性名称,因此我不能直接使用 AutoGenerateColumns。到目前为止,我的想法是使用转换器来获取 MyClass 对象并将它们转换为 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;
}

我将包含网格的 DataContext 设置为 List&lt;MyClass&gt; 对象,并点击了 Convert() 方法,并且从外观上看,DataTable 已创建好,但是当我开始运行应用程序时,DataGrid 是只是空白。这是我的 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>

任何想法为什么 DataGrid 保持为空?

【问题讨论】:

    标签: wpf datagrid datatable


    【解决方案1】:

    当然它是空白的,您正在创建一个没有任何行的DataTable

    如果我正确理解您的(有点奇怪的)设计,每个 MyClass 代表一列及其所有值。要显示它,您必须使用您的类中的值填充 DataTable 的行:

    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;
    }
    

    【讨论】:

    • 那么设计的更好方法是什么?
    • @Tom,我不知道你为什么要这样做,所以这可能是最好的选择。但一般来说,你应该有一些具体类型的对象的集合,其中每个对象代表一行。
    • 我遇到的问题是该对象可能代表 n 列 - 可能是 1,可能是 100 - 每个只有一个或零值(本质上是带有文本框事件的标签)。该解决方案感觉不对...但现在是一个解决方案:)
    猜你喜欢
    • 1970-01-01
    • 2013-03-24
    • 2013-07-28
    • 2011-08-17
    • 1970-01-01
    • 2012-03-06
    • 2018-02-07
    • 2013-06-20
    • 2023-04-06
    相关资源
    最近更新 更多