AnjumSKhan
AnjumSKhan

Reputation: 9827

Copy formatting of a Run to another Run using code

Lets say, I create a Run, and I want to apply exact same formatting of another Run into this new Run.

How to do that using code ?

Upvotes: 0

Views: 83

Answers (1)

Pollitzer
Pollitzer

Reputation: 1620

You can clone the source run into a target run and then change the text of the target run.

// Create a formatted source run
Run sourceRun = new Run("TextOfSourceRun") { FontWeight = FontWeights.Bold, Background = Brushes.Khaki, Foreground = Brushes.Green, FontSize = 25 };

// Clone it
Run targetRun = ElementClone<Run>(sourceRun);

// Change the text of the target run
targetRun.Text = "TextOfTargetRun";

// Insert the target run at the end of the current paragraph
richTextBox.CaretPosition.Paragraph.Inlines.InsertAfter(richTextBox.CaretPosition.Paragraph.Inlines.Last(), targetRun);

public static T ElementClone<T>(T element)
{
    object clonedElement = null;

    MemoryStream memStream = new MemoryStream();
    XamlWriter.Save(element, memStream);

    if (memStream.CanRead)
    {
        memStream.Seek(0, SeekOrigin.Begin);
        clonedElement = XamlReader.Load(memStream);
        memStream.Close();
    }

    return (T)clonedElement;
}

Upvotes: 1

Related Questions