too*_*too 5 c# wpf flowdocument xamlreader xamlwriter
我将FlowDocument与BlockUIContainer和InlineUIContainer元素一起使用,这些元素包含(或作为基类)一些自定义块-SVG,数学公式等。因此,使用Selection.Load(stream,DataFormats.XamlPackage)不能正常工作,因为序列化将删除*的内容UIContainers,除非Child属性是Microsoft参考源中提供的图像:
private static void WriteStartXamlElement(...)
{
...
if ((inlineUIContainer == null || !(inlineUIContainer.Child is Image)) &&
(blockUIContainer == null || !(blockUIContainer.Child is Image)))
{
...
elementTypeStandardized = TextSchema.GetStandardElementType(elementType, /*reduceElement:*/true);
}
...
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,唯一的选择是使用可以完美运行的XamlWriter.Save和XamlReader.Load,序列化和反序列化FlowDocument的所有必需属性和对象,但必须手动实现Copy + Paste作为Copy +的默认实现粘贴使用Selection.Load / Save。
复制/粘贴非常重要,因为它还用于处理RichTextBox控件中或控件之间的元素拖动-无需自定义拖动代码即可操作对象的唯一方法。
这就是为什么我要使用FlowDocument序列化实现复制/粘贴,但是不幸的是,它存在一些问题:
显然,无法将对象从一个文档中删除并添加到另一个文档中(我最近发现了一个死胡同):'InlineCollection'元素无法插入树中,因为它已经是树的子级了。
[TextElementCollection.cs]
public void InsertAfter(TextElementType previousSibling, TextElementType newItem)
{
...
if (previousSibling.Parent != this.Parent)
throw new InvalidOperationException(System.Windows.SR.Get("TextElementCollection_PreviousSiblingDoesNotBelongToThisCollection", new object[1]
{
(object) previousSibling.GetType().Name
}));
...
}
Run Code Online (Sandbox Code Playgroud)
我想考虑在所有需要移到另一个文档的元素中使用反射来设置FrameworkContentElement._parent,但这是不得已而又肮脏的解决方案:
从理论上讲,我只能复制所需的对象:(可选)在选择的开头部分运行带有文本的文本,在and之间的所有段落和内联以及(可能)在结尾部分运行的部分,将它们封装在自定义类中,并使用进行序列化/反序列化XamlReader / XamlWriter。
这是带有部分工作的自定义复制/粘贴代码的自定义RichTextBox控件实现:
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Markup;
namespace FlowMathTest
{
public class CustomRichTextBoxTag: DependencyObject
{
public static readonly DependencyProperty SelectionStartProperty = DependencyProperty.Register(
"SelectionStart",
typeof(int),
typeof(CustomRichTextBoxTag));
public int SelectionStart
{
get { return (int)GetValue(SelectionStartProperty); }
set { SetValue(SelectionStartProperty, value); }
}
public static readonly DependencyProperty SelectionEndProperty = DependencyProperty.Register(
"SelectionEnd",
typeof(int),
typeof(CustomRichTextBoxTag));
public int SelectionEnd
{
get { return (int)GetValue(SelectionEndProperty); }
set { SetValue(SelectionEndProperty, value); }
}
}
public class CustomRichTextBox: RichTextBox
{
public CustomRichTextBox()
{
DataObject.AddCopyingHandler(this, OnCopy);
DataObject.AddPastingHandler(this, OnPaste);
}
protected override void OnSelectionChanged(RoutedEventArgs e)
{
base.OnSelectionChanged(e);
var tag = Document.Tag as CustomRichTextBoxTag;
if(tag == null)
{
tag = new CustomRichTextBoxTag();
Document.Tag = tag;
}
tag.SelectionStart = Document.ContentStart.GetOffsetToPosition(Selection.Start);
tag.SelectionEnd = Document.ContentStart.GetOffsetToPosition(Selection.End);
}
private void OnCopy(object sender, DataObjectCopyingEventArgs e)
{
if(e.DataObject != null)
{
e.Handled = true;
var ms = new MemoryStream();
XamlWriter.Save(Document, ms);
e.DataObject.SetData(DataFormats.Xaml, ms);
}
}
private void OnPaste(object sender, DataObjectPastingEventArgs e)
{
var xamlData = e.DataObject.GetData(DataFormats.Xaml) as MemoryStream;
if(xamlData != null)
{
xamlData.Position = 0;
var fd = XamlReader.Load(xamlData) as FlowDocument;
if(fd != null)
{
var tag = fd.Tag as CustomRichTextBoxTag;
if(tag != null)
{
InsertAt(Document, Selection.Start, Selection.End, fd, fd.ContentStart.GetPositionAtOffset(tag.SelectionStart), fd.ContentStart.GetPositionAtOffset(tag.SelectionEnd));
e.Handled = true;
}
}
}
}
public static void InsertAt(FlowDocument destDocument, TextPointer destStart, TextPointer destEnd, FlowDocument sourceDocument, TextPointer sourceStart, TextPointer sourceEnd)
{
var destRange = new TextRange(destStart, destEnd);
destRange.Text = string.Empty;
// insert partial text of the first run in the selection
if(sourceStart.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
{
var sourceRange = new TextRange(sourceStart, sourceStart.GetNextContextPosition(LogicalDirection.Forward));
destStart.InsertTextInRun(sourceRange.Text);
sourceStart = sourceStart.GetNextContextPosition(LogicalDirection.Forward);
destStart = destStart.GetNextContextPosition(LogicalDirection.Forward);
}
var field = typeof(FrameworkContentElement).GetField("_parent", BindingFlags.NonPublic | BindingFlags.Instance);
while(sourceStart != null && sourceStart.CompareTo(sourceEnd) <= 0 && sourceStart.Paragraph != null)
{
var sourceInline = sourceStart.Parent as Inline;
if(sourceInline != null)
{
sourceStart.Paragraph.Inlines.Remove(sourceInline);
if(destStart.Parent is Inline)
{
field.SetValue(sourceInline, null);
destStart.Paragraph.Inlines.InsertAfter(destStart.Parent as Inline, sourceInline);
}
else
{
var p = new Paragraph();
destDocument.Blocks.InsertAfter(destStart.Paragraph, p);
p.Inlines.Add(sourceInline);
}
sourceStart = sourceStart.GetNextContextPosition(LogicalDirection.Forward);
}
else
{
var sourceBlock = sourceStart.Parent as Block;
field.SetValue(sourceBlock, null);
destDocument.Blocks.InsertAfter(destStart.Paragraph, sourceBlock);
sourceStart = sourceStart.GetNextContextPosition(LogicalDirection.Forward);
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
问题是-是否存在使用XamlReader和XamlWriter为FlowDocument定制复制+粘贴代码的现有解决方案?如何修复上面的代码,以便它不会抱怨其他FlowDocument对象或解决此限制?
编辑:作为一个实验,我实现了2),以便可以将对象从一个FlowDocument移到另一个。上面的代码已更新-所有对“ field”变量的引用。
看来赏金期快要到期了,我在如何实现上述问题上取得了突破,所以我在这里分享一下。
首先,TextRange.Save 有一个“preserveTextElements”参数,可用于序列化 InlineUIContainer 和 BlockUIContainer 元素。此外,这两个控件都不是密封的,因此可以用作自定义 TextElement 实现的基类。
考虑到上述内容:
我创建了一个继承自 InlineUIContainer 的 InlineMedia 元素,该元素使用 XamlReader 和 XamlWriter 将其 Child“手动”序列化为“ChildSource”依赖属性,并从默认序列化器中隐藏原始“Child”
我更改了 CustomRichTextBox 的上述实现,以使用 range.Save(ms, DataFormats.Xaml, true) 复制选择。
您可以注意到,不需要特殊的粘贴处理,因为在交换剪贴板中的原始 Xaml 后,Xaml 可以很好地反序列化,这意味着拖动可以作为来自所有 CustomRichtextBox 控件的复制,而粘贴甚至可以粘贴到普通的 RichTextBox 中。
唯一的限制是,对于所有 InlineMedia 控件,在序列化整个文档之前,需要通过序列化其 Child 来更新 ChildSource 属性,并且我发现无法自动执行此操作(在保存元素之前挂钩到 TextRange.Save)。
我可以忍受这一点,但是没有这个问题的更好的解决方案仍然会获得赏金!
InlineMedia元素代码:
public class InlineMedia: InlineUIContainer
{
public InlineMedia()
{
}
public InlineMedia(UIElement childUIElement) : base(childUIElement)
{
UpdateChildSource();
}
public InlineMedia(UIElement childUIElement, TextPointer insertPosition)
: base(childUIElement, insertPosition)
{
UpdateChildSource();
}
public static readonly DependencyProperty ChildSourceProperty = DependencyProperty.Register
(
"ChildSource",
typeof(string),
typeof(InlineMedia),
new FrameworkPropertyMetadata(null, OnChildSourceChanged));
public string ChildSource
{
get
{
return (string)GetValue(ChildSourceProperty);
}
set
{
SetValue(ChildSourceProperty, value);
}
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public new UIElement Child
{
get
{
return base.Child;
}
set
{
base.Child = value;
UpdateChildSource();
}
}
public void UpdateChildSource()
{
IsInternalChildSourceChange = true;
try
{
ChildSource = Save();
}
finally
{
IsInternalChildSourceChange = false;
}
}
public string Save()
{
if(Child == null)
{
return null;
}
using(var stream = new MemoryStream())
{
XamlWriter.Save(Child, stream);
stream.Position = 0;
using(var reader = new StreamReader(stream, Encoding.UTF8))
{
return reader.ReadToEnd();
}
}
}
public void Load(string sourceData)
{
if(string.IsNullOrEmpty(sourceData))
{
base.Child = null;
}
else
{
using(var stream = new MemoryStream(Encoding.UTF8.GetBytes(sourceData)))
{
var child = XamlReader.Load(stream);
base.Child = (UIElement)child;
}
}
}
private static void OnChildSourceChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var img = (InlineMedia) sender;
if(img != null && !img.IsInternalChildSourceChange)
{
img.Load((string)e.NewValue);
}
}
protected bool IsInternalChildSourceChange { get; private set; }
}
Run Code Online (Sandbox Code Playgroud)
CustomRichTextBox控件代码:
public class CustomRichTextBox: RichTextBox
{
public CustomRichTextBox()
{
DataObject.AddCopyingHandler(this, OnCopy);
}
private void OnCopy(object sender, DataObjectCopyingEventArgs e)
{
if(e.DataObject != null)
{
UpdateDocument();
var range = new TextRange(Selection.Start, Selection.End);
using(var ms = new MemoryStream())
{
range.Save(ms, DataFormats.Xaml, true);
ms.Position = 0;
using(var reader = new StreamReader(ms, Encoding.UTF8))
{
var xaml = reader.ReadToEnd();
e.DataObject.SetData(DataFormats.Xaml, xaml);
}
}
e.Handled = true;
}
}
public void UpdateDocument()
{
ObjectHelper.ExecuteRecursive<InlineMedia>(Document, i => i.UpdateChildSource(), FlowDocumentVisitors);
}
private static readonly Func<object, object>[] FlowDocumentVisitors =
{
x => (x is FlowDocument) ? ((FlowDocument) x).Blocks : null,
x => (x is Section) ? ((Section) x).Blocks : null,
x => (x is BlockUIContainer) ? ((BlockUIContainer) x).Child : null,
x => (x is InlineUIContainer) ? ((InlineUIContainer) x).Child : null,
x => (x is Span) ? ((Span) x).Inlines : null,
x => (x is Paragraph) ? ((Paragraph) x).Inlines : null,
x => (x is Table) ? ((Table) x).RowGroups : null,
x => (x is Table) ? ((Table) x).Columns : null,
x => (x is Table) ? ((Table) x).RowGroups.SelectMany(rg => rg.Rows) : null,
x => (x is Table) ? ((Table) x).RowGroups.SelectMany(rg => rg.Rows).SelectMany(r => r.Cells) : null,
x => (x is TableCell) ? ((TableCell) x).Blocks : null,
x => (x is TableCell) ? ((TableCell) x).BorderBrush : null,
x => (x is List) ? ((List) x).ListItems : null,
x => (x is ListItem) ? ((ListItem) x).Blocks : null
};
}
Run Code Online (Sandbox Code Playgroud)
最后是 ObjectHelper 类 - 访问者助手:
public static class ObjectHelper
{
public static void ExecuteRecursive(object item, Action<object> execute, params Func<object, object>[] childSelectors)
{
ExecuteRecursive<object, object>(item, null, (c, i) => execute(i), childSelectors);
}
public static void ExecuteRecursive<TObject>(object item, Action<TObject> execute, params Func<object, object>[] childSelectors)
{
ExecuteRecursive<object, TObject>(item, null, (c, i) => execute(i), childSelectors);
}
public static void ExecuteRecursive<TContext, TObject>(object item, TContext context, Action<TContext, TObject> execute, params Func<object, object>[] childSelectors)
{
ExecuteRecursive(item, context, (c, i) =>
{
if(i is TObject)
{
execute(c, (TObject)i);
}
}, childSelectors);
}
public static void ExecuteRecursive<TContext>(object item, TContext context, Action<TContext, object> execute, params Func<object, object>[] childSelectors)
{
execute(context, item);
if(item is IEnumerable)
{
foreach(var subItem in item as IEnumerable)
{
ExecuteRecursive(subItem, context, execute, childSelectors);
}
}
if(childSelectors != null)
{
foreach(var subItem in childSelectors.Select(x => x(item)).Where(x => x != null))
{
ExecuteRecursive(subItem, context, execute, childSelectors);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1736 次 |
| 最近记录: |