保存数据库中文本的颜色,并将带有颜色的文本复制到richtextbox中

时间:2013-03-21 12:36:43

标签: c# sql wpf colors richtextbox

我希望在将文本复制到richtextbox时保留文本的格式,我该怎么做? (当您在Microsoft Word文档中复制代码时,代码的颜色将与Visual Studio中的相同(在此处显示http://img4.fotos-hochladen.net/uploads/unbenannta2k46fcjn5.png))

我想将文本保存在sql数据库中,并使用相同的格式(颜色等)重新加载它。我知道如何在数据库中保存和读取数据,但如何使用格式(颜色)保存文本?

2 个答案:

答案 0 :(得分:2)

您还可以将隐藏在RichTextBox.Document中的FlowDocument保存为字符串

public static string ToStringExt(this IDocumentPaginatorSource flowDocument)
{
    return XamlWriter.Save(flowDocument);
}

将其转换为FlowDocument,您可以使用此扩展

public static bool IsFlowDocument(this string xamlString)
{
    if (xamlString.IsNullOrEmpty()) 
        throw new ArgumentNullException();

    if (xamlString.StartsWith("<") && xamlString.EndsWith(">"))
    {
        XmlDocument xml = new XmlDocument();
        try
        {
            xml.LoadXml(string.Format("<Root>{0}</Root>", xamlString));
            return true;
        }
        catch (XmlException)
        {
            return false;
        }
    }
    return false;
}

public static FlowDocument toFlowDocument(this string xamlString)
{
    if (IsFlowDocument(xamlString))
    {
        var stringReader = new StringReader(xamlString);
        var xmlReader = System.Xml.XmlReader.Create(stringReader);

        return XamlReader.Load(xmlReader) as FlowDocument;
    }
    else
    {
        Paragraph myParagraph = new Paragraph();
        myParagraph.Inlines.Add(new Run(xamlString));
        FlowDocument myFlowDocument = new FlowDocument();
        myFlowDocument.Blocks.Add(myParagraph);

        return myFlowDocument;
    }
}

答案 1 :(得分:-1)

使用RichTextBox的Rtf属性

richtextbox1.Rtf =&gt;存储到数据库

从数据库中检索并恢复richtextbox1.Rtf中的值。

相关问题