##前提
環境:VS2019
言語:C# WPF
フレームワーク:MVVM
##最終的に達成したい事
以下のような、クリップボードを監視して履歴を保持するようなアプリケーションを作成しています。
]
アプリケーションを閉じて再度起動した際に、リッチテキストボックスに貼り付けられていた画像をリッチテキストボックスに貼れるようにFlowDocument型に戻してやりたい。
テキストボックスに関してはうまくFlowDocument型に戻せています。
##悩んでいる事
リッチテキストボックスに貼った画像を、次回起動時にFlowDocument型にして復元することができない。
##現状
リッチテキストボックスのDocumentプロパティ(FlowDocument型)をバイナリーへそのまま変換する事ができないので、以下の手順で変換・復元を行う。
- XamlWriteを使用してXamlへ一旦文字列変換する
- アプリケーション起動時に、そのXaml文字列をFlowDocumentへ変換する
- リッチテキストボックスのDocumentプロパティへバインドさせてやることで内容を復元する
具体例として、
「Teratail」という文字列を持ったFlowDocumentをXaml文字列へ変換した場合、以下のようなXamlになります。
Xaml
1<FlowDocument xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"> 2 <Paragraph>Teratail</Paragraph> 3</FlowDocument>
これであれば、難なくFlowDocument型へ戻すことができます。
念の為ですが、以下の様に表示されます。
画像を持ったFlowDocumentを変換した場合、以下のようなXamlになります。
Xaml
1<FlowDocument xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:swi="clr-namespace:System.Windows.Interop;assembly=PresentationCore"> 2 <Paragraph> 3 <Image> 4 <Image.Source> 5 <swi:InteropBitmap /> 6 </Image.Source> 7 </Image> 8 </Paragraph> 9</FlowDocument>
アプリケーション起動中であれば、FlowDocumentを生成するので以下の様に表示できます。
]
一致するコンストラクターが型 'System.Windows.Interop.InteropBitmap' に見つかりません。この型は、引数または FactoryMethod ディレクティブを使用して構築できます。
どのようにすれば、リッチテキストボックスの画像を復元できるのでしょうか。
##コード
FlowDocument ⇔ Xaml の変換には以下のコードを使用しています。
どこかのStackOverFlowの記事のロジックを持ってきていましたが、どこからかは失念してしまいました。
C#
1/// <summary> 2/// FlowDocumentをXaml文字列へ変換 3/// </summary> 4/// <param name="flowDocument"></param> 5/// <returns></returns> 6public static string ToXamlString(this IDocumentPaginatorSource flowDocument) 7{ 8 return XamlWriter.Save(flowDocument); 9} 10/// <summary> 11/// Xaml文字列をFlowDocumentへ変換 12/// </summary> 13/// <param name="xamlString"></param> 14/// <returns></returns> 15public static FlowDocument ToFlowDocument(this string xamlString) 16{ 17 if (IsFlowDocument(xamlString)) 18 { 19 var stringReader = new StringReader(xamlString); 20 var xmlReader = XmlReader.Create(stringReader); 21 22 return XamlReader.Load(xmlReader) as FlowDocument; 23 } 24 else 25 { 26 var myParagraph = new Paragraph(); 27 myParagraph.Inlines.Add(new Run(xamlString)); 28 var myFlowDocument = new FlowDocument(); 29 myFlowDocument.Blocks.Add(myParagraph); 30 31 return myFlowDocument; 32 } 33} 34/// <summary> 35/// 36/// </summary> 37/// <param name="xamlString"></param> 38/// <returns></returns> 39private static bool IsFlowDocument(this string xamlString) 40{ 41 if (string.IsNullOrEmpty(xamlString)) 42 { 43 throw new ArgumentNullException(); 44 } 45 46 if (xamlString.StartsWith("<") && xamlString.EndsWith(">")) 47 { 48 var xml = new XmlDocument(); 49 try 50 { 51 xml.LoadXml(string.Format("<Root>{0}</Root>", xamlString)); 52 return true; 53 } 54 catch (XmlException) 55 { 56 return false; 57 } 58 } 59 return false; 60}
##他に参考にしたもの
以下のソースを使用して変換を試みましたが、うまく扱えませんでした。
StackOverFlow - C#WPFは、richtextboxに貼り付けられたBitmapImageをバイナリに変換します。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。