Domanda

Sto cercando un buon modo pulito per consentire la copia di testo da un RichTextBox visualizzazione di emoticon. Pensate a skype, dove è possibile selezionare una chat e sarà copiare le immagini emoticon e convertirle in loro rappresentazioni testuali (immagine Smiley a :), ecc). Sto usando il modello MVVM.

È stato utile?

Soluzione

Non so di un modo per configurare l'analisi di RichTextBox contenuti in testo. Qui di seguito è un modo che utilizza XML LINQ. Le espressioni regolari potrebbe funzionare meglio, ma faccio schifo a loro. Metodo Passo ConvertToText teh FlowDocument della tua RichTextBox.

private static string ConvertToText(FlowDocument flowDocument)
{
    TextRange textRangeOriginal =
        new TextRange(flowDocument.ContentStart, flowDocument.ContentEnd);

    string xamlString;
    using (MemoryStream memoryStreamOriginal = new MemoryStream())
    {
        textRangeOriginal.Save(memoryStreamOriginal, DataFormats.Xaml);
        xamlString = ASCIIEncoding.Default.GetString(memoryStreamOriginal.ToArray());
    }

    XElement root = XElement.Parse(xamlString);

    IEnumerable<XElement> smilies =
        from element in root.Descendants()
        where (string)element.Attribute("FontFamily") == "Wingdings" && IsSmiley(element.Value)
        select element;

    foreach (XElement element in smilies.ToList())
    {
        XElement textSmiley = new XElement(element.Name.Namespace + "Span",
                                           new XElement(element.Name.Namespace + "Run", GetTextSmiley(element.Value)));
        element.ReplaceWith(textSmiley);
    }

    using (MemoryStream memoryStreamChanged = new MemoryStream())
    {
        StreamWriter streamWriter = new StreamWriter(memoryStreamChanged);
        streamWriter.Write(root.ToString(SaveOptions.DisableFormatting));
        streamWriter.Flush();
        FlowDocument flowDocumentChanged = new FlowDocument();
        TextRange textRangeChanged =
            new TextRange(flowDocument.ContentStart, flowDocument.ContentEnd);
        textRangeChanged.Load(memoryStreamChanged, DataFormats.Xaml);
        return textRangeChanged.Text;
    }
}

private static string GetTextSmiley(string value)
{
    switch (value)
    {
        case "J" :
            return ":)";
        case "K" :
            return ":|";
        case "L" :
            return ":(";
        default :
            throw new ArgumentException();
    }
}

private static bool IsSmiley(string value)
{
    return value == "J" || value == "K" || value == "L";
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top