我想在WPF应用程序中突出显示数据网格中的字符串。
在WinForms中,有一个CellPainting事件可以帮助我们实现这一目的。我无法在WPF中找到任何内容。
我想突出显示单元格中存在的TEXT部分,而不是整个单元格。
任何帮助将不胜感激。
你可以:
添加 DataGridTemplateColumn。在模板中放置一个 TextBlock。然后,选项 1:插入到您的运行文本块中。设置它们的格式。并将运行绑定到您的数据。选项2:通过转换器等在程序代码中设置TextBlock的内容。
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock>
<Run Text="{Binding xx}" Background="Yellow" />
<Run Text="{Binding yy}" />
</TextBlock>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
代码
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;
}
}
Run Code Online (Sandbox Code Playgroud)
评论:你也可以像WinForms一样绘图,但没有必要,不推荐。