從你的問題中有限的信息,我猜你的數據表中包含了我不推薦,因爲它會讓你的代碼,以便更復雜的自定義類型的列。但是,如果你決定這樣做,你可以實現自定義列類型來處理。我還沒有嘗試過,但這個鏈接看起來很有希望: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