使用 dataGrid 的 AutoGeneratingColumn 事件来设置图像。
在 xaml 中定义数据模板
<DataTemplate x:Key="ActivaStatusColumnTemplate">
<Image DataContext="{Binding}" >
<Image.Style>
<Style TargetType="{x:Type Image}">
<Setter Property="Source" Value="red.png" />
<Style.Triggers>
<DataTrigger Value="On" Binding="{Binding}">
<Setter Property="Source" Value="green.png"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Image.Style>
</Image>
</DataTemplate>
//后面的代码
private void dgView_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
if (e.Column.Header.ToString() == "ActiveStatus")
{
// Create a new template column.
MyDataGridTemplateColumn templateColumn = new MyDataGridTemplateColumn();
templateColumn.CellTemplate = (DataTemplate)Resources["ActivaStatusColumnTemplate"];
templateColumn.ColumnName = e.PropertyName; // so it knows from which column to get binding data
e.Column = templateColumn;
e.Column.Header = "ActiveStatus";
}
}
//定义覆盖DataGridTemplateColumn的类
/// <summary>
/// Custom class derieved fromt the DataGridTemplateColumn to set the property name.
/// </summary>
public class MyDataGridTemplateColumn : DataGridTemplateColumn
{
public string ColumnName
{
get;
set;
}
protected override System.Windows.FrameworkElement GenerateElement(DataGridCell cell, object dataItem)
{
// The DataGridTemplateColumn uses ContentPresenter with your DataTemplate.
ContentPresenter cp = (ContentPresenter)base.GenerateElement(cell, dataItem);
// Reset the Binding to the specific column. The default binding is to the DataRowView.
BindingOperations.SetBinding(cp, ContentPresenter.ContentProperty, new Binding(this.ColumnName));
return cp;
}
}
参考
http://social.msdn.microsoft.com/Forums/en/wpf/thread/8b2e94b7-3c44-4642-8acc-851de5285062