can you show me how use cell styles to modify an existing DataGridTextColumn such that it displays text along with an image next to it?
Here:
<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>
With some more work, you can define these templates and style as Resources
in your application and reuse them every time.
With regards to the image source, you could use an Attached Property
to define it in the DataGridTextColumn
, or even the Tag
property.
Edit: Example with an attached property:
<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>
Code:
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;
}
}