从你的问题中有限的信息,我猜你的数据表中包含了我不推荐,因为它会让你的代码,以便更复杂的自定义类型的列。但是,如果你决定这样做,你可以实现自定义列类型来处理。我还没有尝试过,但这个链接看起来很有希望:Bind DataTable to WPF DataGrid using DataGridTemplateColumn Programatically
您也可以使用值转换器来实现相同的目的。下面的示例传递列索引作为参数,但您也可以使用某种格式(例如0值,意思是第0列,属性值)传递您感兴趣的属性。
XAML:
<Window x:Class="GridCellDemo.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Controls="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit"
xmlns:GridCellDemo="clr-namespace:GridCellDemo"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<GridCellDemo:CellConverter x:Key="CellConverter" />
</Window.Resources>
<Grid>
<Controls:DataGrid ItemsSource="{Binding Data}" AutoGenerateColumns="False">
<Controls:DataGrid.Columns>
<Controls:DataGridTextColumn Header="Col 0" Binding="{Binding ., Converter={StaticResource CellConverter}, ConverterParameter=0}" />
<Controls:DataGridTextColumn Header="Col 1" Binding="{Binding ., Converter={StaticResource CellConverter}, ConverterParameter=1}" />
</Controls:DataGrid.Columns>
</Controls:DataGrid>
</Grid>
</Window>
后面的代码:
using System;
using System.Data;
using System.Windows;
using System.Windows.Data;
namespace GridCellDemo
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
DataContext = this;
}
public DataTable Data
{
get
{
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Col0", typeof(GridCell)));
dt.Columns.Add(new DataColumn("Col1", typeof(GridCell)));
DataRow row0 = dt.NewRow();
dt.Rows.Add(row0);
row0["Col0"] = new GridCell() { Value = "R0C0" };
row0["Col1"] = new GridCell() { Value = "R0C1" };
DataRow row1 = dt.NewRow();
dt.Rows.Add(row1);
row1["Col0"] = new GridCell() { Value = "R1C0" };
row1["Col1"] = new GridCell() { Value = "R1C1" };
return dt;
}
}
}
public class GridCell
{
public string Value { get; set; }
public Guid Id { get; set; }
}
public class CellConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
DataRowView drv = value as DataRowView;
if (drv == null)
{
return string.Empty;
}
int columnIndex = int.Parse(parameter.ToString());
GridCell gridCell = drv[columnIndex] as GridCell;
return gridCell.Value;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
显示您绑定代码。 – 2011-03-15 13:58:43
您是否将网格的itemsource属性分配给GridCell集合。您可以发布您的绑定代码。 – Novice 2011-03-15 14:00:01
添加了绑定代码片段。 – 2011-03-15 14:02:48