【发布时间】: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<MyClass> 对象,并点击了 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 保持为空?
【问题讨论】: