WPFはRichTextBoxの画像挿入と行間調整を実現
WPFにはWinformと同じ形式のものが多いが,コントロールの使用には驚くことが多い.RichTextBoxは一例です.はい、WPFではこのコントロールに対してWinformが難しい効果をたくさん作ることができます.
例えばRichTextBoxに画像を挿入すると、winform時代にはクリップボードをコピーして貼り付けるという下手な方法のほか、RichTextBoxコントロールを書き直してカスタマイズすることになりました.これには優れたプログラミング能力が必要です.しかし、WPFでは、いくつかのコードを追加するだけでできます.
XAMLにRichTextBoxに画像を追加すると、以下のようになります.
これでコントロールに画像を追加しました.
メモ:FlowDocumentのLineHeightプロパティは、テキスト段落の間隔です.デフォルトの間隔が大きいので、ここで調整します!
もちろん、プログラムが実行されている間にボタンをクリックして画像を選択して追加する必要があるため、必ずしも要求を完全に満たすことはできません.コードは次のとおりです.
例えばRichTextBoxに画像を挿入すると、winform時代にはクリップボードをコピーして貼り付けるという下手な方法のほか、RichTextBoxコントロールを書き直してカスタマイズすることになりました.これには優れたプログラミング能力が必要です.しかし、WPFでは、いくつかのコードを追加するだけでできます.
XAMLにRichTextBoxに画像を追加すると、以下のようになります.
<!--
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->
<
RichTextBox
HorizontalAlignment
="Left"
Margin
="90,12,0,0"
Name
="richTextBox1"
>
<
RichTextBox.Document
>
<
FlowDocument
Focusable
="True"
LineHeight
="5"
>
<
Paragraph
x:Name
="gara"
>
<
Image
Source
="D:\1342892_10.jpg"
Focusable
="True"
Height
="50"
Stretch
="Uniform"
/>
<
Run
Text
=" "
></
Run
>
<
Run
Text
=" "
></
Run
>
</
Paragraph
>
<
Paragraph
x:Name
="gara1"
>
<
Run
Text
=" "
></
Run
>
<
Run
Text
=" "
></
Run
>
</
Paragraph
>
</
FlowDocument
>
</
RichTextBox.Document
>
</
RichTextBox
>
これでコントロールに画像を追加しました.
メモ:FlowDocumentのLineHeightプロパティは、テキスト段落の間隔です.デフォルトの間隔が大きいので、ここで調整します!
もちろん、プログラムが実行されている間にボタンをクリックして画像を選択して追加する必要があるため、必ずしも要求を完全に満たすことはできません.コードは次のとおりです.
<!--
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->
private
void
AddJPG_Click(
object
sender, RoutedEventArgs e) {
string
filepath
=
""
;
string
filename
=
""
; OpenFileDialog openfilejpg
=
new
OpenFileDialog(); openfilejpg.Filter
=
"
jpg (*.jpg)|*.jpg|gif (*.gif)|*.gif
"
; openfilejpg.FilterIndex
=
0
; openfilejpg.RestoreDirectory
=
true
; openfilejpg.Multiselect
=
false
;
if
(openfilejpg.ShowDialog()
==
true
) { filepath
=
openfilejpg.FileName; Image img
=
new
Image(); BitmapImage bImg
=
new
BitmapImage(); img.IsEnabled
=
true
; bImg.BeginInit(); bImg.UriSource
=
new
Uri(filepath, UriKind.Relative); bImg.EndInit(); img.Source
=
bImg;
//
MessageBox.Show(bImg.Width.ToString() + "," + bImg.Height.ToString());
/*
if (bImg.Height > 100 || bImg.Width > 100) { img.Height = bImg.Height * 0.2; img.Width = bImg.Width * 0.2; }
*/
img.Stretch
=
Stretch.Uniform;
//
new
InlineUIContainer(img, richTextBox1.Selection.Start);
//
} }