WPF往RichTextBox添加图片及调整行距

 

WPF里面虽然很多形式上跟Winform一样,但是控件的使用上面还是会有很多诧异。RichTextBox就是一个例子,是的,在WPF里面对这个控件可以做很多Winform很难做的效果出来。

比如在对RichTextBox插入图片,winform时代除了用复制粘贴这种借助剪贴板的差劲方法之外就是要重写和自定义RichTextBox控件了。这就需要高超的编程能力了。但在WPF里面,只需要加几个代码就能搞定了。

在XAML里面添加图片到RichTextBox可以如下所示:

        <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 属性是文字段落的间距。默认间距很大,所以这里调整一下!

 

当然,这样未必能够完全满足要求,因为有时候我们需要在程序运行的时候点击按钮选取图片进行添加。代码如下:

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); //插入图片到选定位置

            }

        }

这样就插入了一张图片到RichTextBox里了,是不是很简单呢!

你可能感兴趣的:(编程,WPF,WinForm)