我正在寻找一种好的,干净的方法来启用从显示表情符号的richtextbox中复制文本。想想skype,你可以在那里选择一个聊天,它将复制表情图像并将它们转换为文本表示(笑脸图像到:)等)。我正在使用MVVM模式。
答案 0 :(得分:4)
我不知道如何配置将RichTextBox内容解析为文本。下面是使用xml linq的一种方法。正则表达式可能会更好,但我很沮丧。传递ConvertToText方法,以及RichTextBox的FLowDocument。
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";
}