Reputation:
I want to highlight the strings in data grid in a WPF application.
In WinForms there is a CellPainting
event that helps us in fulfilling this purpose.
I am unable to locate anything in WPF.
I want to highlight part of TEXT that is present in a cell, not whole cell.
Any help will be appreciated.
Upvotes: 5
Views: 3141
Reputation: 6462
You Can:
add a DataGridTemplateColumn. In the template place a TextBlock. Then, Option 1: insert in your textBlock Run's. Set their Format. And Bind the Run's to your Data. Option 2: set the Content of TextBlock in procedural code, via converter ect.
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock>
<Run Text="{Binding xx}" Background="Yellow" />
<Run Text="{Binding yy}" />
</TextBlock>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
XAML
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<DataTemplate.Resources>
<myns:ConvertToFormatedRuns xmlns:myns="clr-namespace:YourProjectName" />
</DataTemplate.Resources>
<Label>
<Label.Content>
<MultiBinding Converter={StaticResource ConvertToFormatedRuns}>
<Binding Path="xxx" />
<Binding Path="yyy" />
</MultiBinding>
</Label.Content>
</Label>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
CODE
public class ConvertToFormatedRuns : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
var tb = new TextBlock();
tb.Inlines.Add(new Run() { Text = (string)values[0], Background = Brushes.Yellow });
tb.Inlines.Add(new Run() { Text = (string)values[1]});
return tb;
}
}
Comment: you can also Drawning like WinForms, but is Unnecessary and not recommended.
Upvotes: 3