你能告诉我如何使用单元格样式来修改现有的 DataGridTextColumn 以便它显示文本以及旁边的图像吗?
这里:
<DataGridTextColumn Binding="{Binding LastName}">
<DataGridTextColumn.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="DataGridCell">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="16"/>
</Grid.ColumnDefinitions>
<ContentPresenter ContentSource="Content"/>
<Image Source="/Images/Homer.jpg" Grid.Column="1"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</DataGridTextColumn.CellStyle>
</DataGridTextColumn>
通过更多的工作,您可以像Resources
在应用程序中一样定义这些模板和样式,并且每次都可以重用它们。
关于图像源,您可以使用 anAttached Property
来定义它DataGridTextColumn
,甚至是Tag
属性。
编辑:带有附加属性的示例:
<DataGrid ...>
<DataGrid.Resources>
<ControlTemplate TargetType="DataGridCell" x:Key="TextAndImageDataGridCellTemplate">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="16"/>
</Grid.ColumnDefinitions>
<ContentPresenter ContentSource="Content"/>
<Image Source="{Binding Column.(local:GridColumnProperties.ImageSource), RelativeSource={RelativeSource TemplatedParent}}" Grid.Column="1"/>
</Grid>
</ControlTemplate>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding LastName}"
local:GridColumnProperties.ImageSource="/Images/Homer.jpg">
<DataGridTextColumn.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="Template" Value="{StaticResource TextAndImageDataGridCellTemplate}"/>
</Style>
</DataGridTextColumn.CellStyle>
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
代码:
public static class GridColumnProperties
{
public static readonly DependencyProperty ImageSourceProperty = DependencyProperty.RegisterAttached("ImageSource", typeof(ImageSource), typeof(GridColumnProperties), new PropertyMetadata());
public static void SetImageSource(DependencyObject obj, ImageSource value)
{
obj.SetValue(ImageSourceProperty, value);
}
public static ImageSource GetImageSource(DependencyObject obj)
{
return obj.GetValue(ImageSourceProperty) as ImageSource;
}
}