我想在DataGrid中更改richTextBox中特定单词的颜色。 但我不知道如何在DataGrid中访问richTextBox。 我无法访问RichTextBox名称的Rchtxt。 有人知道吗?或另一种改变颜色的方法。
这是我的代码:
<DataGrid Name="Data"
AutoGenerateColumns="False" IsReadOnly="True">
<DataGrid.Columns>
<DataGridTemplateColumn Header="contents" x:Name="headerb">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<RichTextBox x:Name="Rchtxt" TextChanged="rtb_TextChanged">
<FlowDocument Name="rtbFlowDoc" PageWidth="{Binding ElementName=rtb, Path=ActualWidth}">
<Paragraph>
<Run Text="{Binding Path=BODY}" />
</Paragraph>
</FlowDocument>
</RichTextBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
private void rtb_TextChanged(object sender, TextChangedEventArgs e)
{
RichTextBox rtb = (RichTextBox)sender;
string find = "apple";
String text = new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd).Text;
if (text.Contains(find))
{
foreach (Match match in Regex.Matches(text, find))
{
TextPointer myTextPointer1 = rtb.Document.ContentStart.GetPositionAtOffset(match.Index);
TextPointer myTextPointer2 = myTextPointer1.GetPositionAtOffset(find.Length);
rtb.Selection.Select(myTextPointer1, myTextPointer2);
rtb.Selection.ApplyPropertyValue(TextElement.ForegroundProperty, new media.SolidColorBrush(media.Color.FromArgb(255, 255, 0, 0)));
};
}
}