我正在开发的应用程序中有一个 RichTextBox 控件,我将它与 ToolBar 一起用于创建富文本编辑器。我实现的一个功能是用户插入图像的能力,现在值得注意的是,RichTextBox 的输出是 RTF。
当用户插入图像时,我使用以下代码将图像添加到文档中,然后将 ResizeAdorner(此处为RichTextBox Resizing Adorner的示例)添加到允许用户调整大小的图像中。当用户保存并加载文档时,图像的大小会正确保留。
private void BtnInsertImage_OnClick(object sender, RoutedEventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Multiselect = false;
ofd.CheckFileExists = true;
ofd.CheckPathExists = true;
ofd.Filter = "Image files (*.png;*.jpg;*.jpeg;*.gif;*.bmp)|*.png;*.jpg;*.jpeg;*.gif;*.bmp";
ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
ofd.Title = "Insert Image";
if (ofd.ShowDialog() == true)
{
BitmapImage bitmap = new BitmapImage(new Uri(ofd.FileName, UriKind.RelativeOrAbsolute))
{
CacheOption = BitmapCacheOption.OnLoad
};
Image image = new Image();
image.IsEnabled = true;
image.Source = bitmap;
image.Width = bitmap.Width;
image.Height = bitmap.Height;
image.Loaded += this.ImageOnLoaded;
image.Stretch = Stretch.Uniform;
InlineUIContainer container = new InlineUIContainer(image, this.rtbEditor.Selection.Start);
Paragraph paragraph = new Paragraph(container);
var doc = this.rtbEditor.Document;
doc.Blocks.Add(paragraph);
}
}
private void ImageOnLoaded(object sender, RoutedEventArgs routedEventArgs)
{
var img = sender as Image;
if (img != null)
{
var al = AdornerLayer.GetAdornerLayer(img);
if (al != null)
{
al.Add(new ResizingAdorner(img));
}
}
}
问题和疑问是,当加载文档时,我无法弄清楚如何将 ResizingAdorner 添加到文档中的图像中。我正在使用附加属性来加载文档内容,下面的代码是加载文档的部分:
var stream = new MemoryStream(Encoding.UTF8.GetBytes(GetDocumentXaml(richTextBox)));
var doc = new FlowDocument();
var range = new TextRange(doc.ContentStart, doc.ContentEnd);
range.Load(stream, DataFormats.Xaml);
richTextBox.Document = doc;
任何人都可以帮助我如何将 ResizingAdorner 添加到加载的文档中的任何图像中吗?