atnaf99
atnaf99

Reputation: 1

Is there a correct way to handle Inlines in DataGridTemplateColumn TextBlock?

I'm using a TextBlockFormatter to highlight specific parts of text in a DataGridTemplateColumn -> TextBlock

DataGridTemplateColumn

<DataGridTemplateColumn Width="2.5*" Header="{DynamicResource TEXT}" >
    <DataGridTemplateColumn.CellTemplate>
         <DataTemplate>
             <TextBlock base:TextBlockFormatter.FormattedText="{Binding prettyText}"                   TextWrapping="Wrap" />
         </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

TextBlockFormatter:

public class TextBlockFormatter
{
    public static readonly DependencyProperty FormattedTextProperty = DependencyProperty.RegisterAttached(
        "FormattedText",
        typeof(string),
        typeof(RequestTextBlockFormatter),
        new FrameworkPropertyMetadata(null, OnFormattedTextChanged));

    public static void SetFormattedText(UIElement element, string value)
    {
        element.SetValue(FormattedTextProperty, value);
    }

    private static void OnFormattedTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        TextBlock textblock = (TextBlock)d;
        //textblock.Inlines.Clear();
        List<SplitText> splitTexts = TranslationActions.getSplitetTextFromString(e.NewValue.ToString());

        Color textColor = SomeColor;

        foreach (SplitText splitText in splitTexts)
        {
            FontWeight fontWeight = Convert.ToBoolean(splitText.isBold) ? FontWeights.Bold : FontWeights.Normal;
            FontStyle fontStyle = splitText.isItalic ? FontStyles.Italic : FontStyles.Normal;
                
            if(splitText.isColor) 
            {
                textblock.Inlines.Add(new Run(splitText.text){Foreground = new SolidColorBrush(textColor), FontWeight = fontWeight,FontStyle = fontStyle });
            }
            else
            {
                textblock.Inlines.Add(new Run(splitText.text){FontWeight = fontWeight,FontStyle = fontStyle });
            }
       }
    }
}

After about 12 Rows in the DataGrid the TextBlock alread has Inlines and starts repeating data. Is there a way to prevent this without clearing the Inlines every time?

Upvotes: 0

Views: 55

Answers (1)

M Kloster
M Kloster

Reputation: 698

Either you have to build the new Runs from scratch each time (by clearing textblock.Inlines), or you will have to compare the new formatted text to the old one and only change what needs to be changed - which is a much more complicated task.

Upvotes: 0

Related Questions