save the color of a text in a database and copy text with color into a richtextbox

无人久伴 提交于 2019-12-11 04:33:38

问题


I want to maintain the format of a text when i copy it into a richtextbox, How can i do this? (When you copy code in a microsoft word document, the color of the code will be the same as in Visual studio (show here http://img4.fotos-hochladen.net/uploads/unbenannta2k46fcjn5.png ))

And i want to save the text in a sql database and reload it with the same format(colors, etc.). I know how to save and read data in a database but how can i save the text with the format(color)?


回答1:


you could also save the FlowDocument which is hiden in RichTextBox.Document as string

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

to convert it back as FlowDocument you can use this extensions

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;
    }
}



回答2:


Use the Rtf property of the RichTextBox

richtextbox1.Rtf => Store to database

Retrieve from database and restore value in richtextbox1.Rtf.



来源:https://stackoverflow.com/questions/15547738/save-the-color-of-a-text-in-a-database-and-copy-text-with-color-into-a-richtextb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!