让我们说,我创建了一个Run
,我希望将另一个Run
的完全相同的格式应用到这个新Run
中。
如何使用代码?
答案 0 :(得分:1)
您可以将源运行克隆到目标运行中,然后更改目标运行的文本。
// 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;
}