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里了,是不是很简单呢!

 

原文在此:http://blogs.msdn.com/jfoscoding/archive/2006/01/14/512825.aspx 

这里仅整理出其中的知识点:
1. 取得已被选中的内容:
(1)使用 RichTextBox.Document.Selection属性
(2)访问RichTextBox.Document.Blocks属性的“blocks”中的Text

2. 在XAML中增加内容给RichTextBox:
<RichTextBox IsSpellCheckEnabled="True">
   <FlowDocument>
        <Paragraph>
<!-- 这里加上你的内容 -->
          This is a richTextBox. I can <Bold>Bold</Bold>, <Italic>Italicize</Italic>, <Hyperlink>Hyperlink stuff</Hyperlink> right in my document.
        </Paragraph>
   </FlowDocument>
</RichTextBox>

3. 缩短段间距,类似<BR>,而不是<P>
方法是使用Style定义段间距:
    <RichTextBox>
        <RichTextBox.Resources>
          <Style TargetType="{x:Type Paragraph}">
            <Setter Property="Margin" Value="0"/>
          </Style>
        </RichTextBox.Resources>
        <FlowDocument>
          <Paragraph>
            This is my first paragraph... see how there is...
          </Paragraph>
          <Paragraph>
            a no space anymore between it and the second paragraph?
          </Paragraph>
        </FlowDocument>
      </RichTextBox>

4. 从文件中读出纯文本文件后放进RichTextBox或直接将文本放进RichTextBox中:
private void LoadTextFile(RichTextBox richTextBox, string filename)
{
    richTextBox.Document.Blocks.Clear();
    using (StreamReader streamReader = File.OpenText(filename)) {
           Paragraph paragraph = new Paragraph();
           paragraph.Text = streamReader.ReadToEnd();
           richTextBox.Document.Blocks.Add(paragraph);
    }
}

private void LoadText(RichTextBox richTextBox, string txtContent)
{
    richTextBox.Document.Blocks.Clear();
    Paragraph paragraph = new Paragraph();
    paragraph.Text = txtContent;
    richTextBox.Document.Blocks.Add(paragraph);
}
5. 取得指定RichTextBox的内容:
private string GetText(RichTextBox richTextBox) 
{
        TextRange textRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);
        return textRange.Text;
}
6. 将RTF (rich text format)放到RichTextBox中:
private static void LoadRTF(string rtf, RichTextBox richTextBox)
        {
            if (string.IsNullOrEmpty(rtf)) {
                throw new ArgumentNullException();
            }
            TextRange textRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);
            using (MemoryStream rtfMemoryStream = new MemoryStream()) {
                using (StreamWriter rtfStreamWriter = new StreamWriter(rtfMemoryStream)) {
                    rtfStreamWriter.Write(rtf);
                    rtfStreamWriter.Flush();
                    rtfMemoryStream.Seek(0, SeekOrigin.Begin);
//Load the MemoryStream into TextRange ranging from start to end of RichTextBox.
                    textRange.Load(rtfMemoryStream, DataFormats.Rtf);
                }
            }
        }
7. 将文件中的内容加载为RichTextBox的内容
        private static void LoadFile(string filename, RichTextBox richTextBox)
        {
            if (string.IsNullOrEmpty(filename)) {
                throw new ArgumentNullException();
            }
            if (!File.Exists(filename)) {
                throw new FileNotFoundException();
            }
            using (FileStream stream = File.OpenRead(filename)) {
                TextRange documentTextRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);
                string dataFormat = DataFormats.Text;
                string ext = System.IO.Path.GetExtension(filename);
                if (String.Compare(ext, ".xaml",true) == 0) {
                    dataFormat = DataFormats.Xaml;
                }
                else if (String.Compare(ext, ".rtf", true) == 0) {
                    dataFormat = DataFormats.Rtf;
                }
                documentTextRange.Load(stream, dataFormat);
            }        
        }
8. 将RichTextBox的内容保存为文件:
        private static void SaveFile(string filename, RichTextBox richTextBox)
        {
            if (string.IsNullOrEmpty(filename)) {
                throw new ArgumentNullException();
            }
            using (FileStream stream = File.OpenWrite(filename)) {
                TextRange documentTextRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);
                string dataFormat = DataFormats.Text;
                string ext = System.IO.Path.GetExtension(filename);
                if (String.Compare(ext, ".xaml", true) == 0) {
                    dataFormat = DataFormats.Xaml;
                }
                else if (String.Compare(ext, ".rtf", true) == 0) {
                    dataFormat = DataFormats.Rtf;
                }
                documentTextRange.Save(stream, dataFormat);
            }
        }
9. 做个简单的编辑器:
  <!-- Window1.xaml -->
  <DockPanel>
    <Menu DockPanel.Dock="Top">
      <MenuItem Header="_File">
        <MenuItem Header="_Open File" Click="OnOpenFile"/>
        <MenuItem Header="_Save" Click="OnSaveFile"/>
        <Separator/>
        <MenuItem Header="E_xit" Click="OnExit"/>
      </MenuItem>      
    </Menu>
    <RichTextBox Name="richTextBox1"></RichTextBox>     
  </DockPanel>
        // Window1.xaml.cs
        private void OnExit(object sender, EventArgs e) {
            this.Close();
        }
        private void OnOpenFile(object sender, EventArgs e) {
            Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();
            ofd.Filter = "Text Files (*.txt; *.xaml; *.rtf)|*.txt;*.xaml;*.rtf";
            ofd.Multiselect = false;
            if (ofd.ShowDialog() == true) {
                LoadFile(ofd.SafeFileName, richTextBox1);
            }
        }
        private void OnSaveFile(object sender, EventArgs e) {
            Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog();
            sfd.Filter = "Text Files (*.txt; *.xaml; *.rtf)|*.txt;*.xaml;*.rtf";
            if (sfd.ShowDialog() == true) {
                SaveFile(sfd.SafeFileName, richTextBox1);
            }
        }
心中时常装有一盘人生的大棋,天作棋盘,星作棋子,在斗转星移中,只有不断地搏击人生,人生才有意义,生命才能彰显光辉,才能收获一分永恒。
 


本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/267405.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

前端自动化测试工具:SlimerJS、phantomJS 和 CasperJS

对于富客户端的 Web 应用页面&#xff0c;自动登录、页面修改、抓取页面内容、屏幕截图、页面功能测试…面对这些需求&#xff0c;使用后端语言需要花费不少的精力才能实现。此时 SlimerJS、phantomJS 或 CasperJS 或许是更好的一种选择。 一、PhantomJS 和 SlimerJS PhantomJS…

java 封装 继承 堕胎_Java的继承、封装和多态

一、继承继承就是子类继承父类的特征和行为&#xff0c;使得子类对象(实例)具有父类的实例域和方法&#xff0c;或子类从父类继承方法&#xff0c;使得子类具有父类相同的行为。继承的特性子类拥有父类非 private 的属性、方法。子类可以拥有自己的属性和方法&#xff0c;即子类…

HTML5学习笔记简明版(4):新元素之video,audio,meter,datalist,keygen,output

video 通过<video>标签&#xff0c;我们可以抛弃最近不怎么讨好的Flash&#xff0c;直接在页面中播放视频文件。视频文件自然是最符合语义化的文件格式&#xff0c;但该元素标签同样支持音频与图片。 过去(及目前)&#xff0c;我们通常要使用类似下面这样繁冗丑陋的代码来…

P2782 友好城市

题目描述 有一条横贯东西的大河&#xff0c;河有笔直的南北两岸&#xff0c;岸上各有位置各不相同的N个城市。北岸的每个城市有且仅有一个友好城市在南岸&#xff0c;而且不同城市的友好城市不相同。每对友好城市都向政府申请在河上开辟一条直线航道连接两个城市&#xff0c;但…

五个在线图形工具创建简单的设计元素

有很多网站可以为图形元素生成提供服务&#xff0c;但获得非常好的工具并不容易。这就是为什么我共享五个在线的图形工具的原因 Logotype Maker 这是一个简单而自由的做标志的Web工具&#xff0c;它可以帮助您创建一个标志 BgPatterns BgPatterns按几次按键&#xff0c;做背景图…

java shape类_Java——Shape类

Description定义一个形状类Shape&#xff0c;提供计算周长getPerimeter()和面积getArea()的函数定义一个子类正方形类Square继承自Shape类&#xff0c;拥有边长属性&#xff0c;提供构造函数&#xff0c;能够计算周长getPerimeter()和面积getArea()定义一个子类长方形类Rectang…

sulin Python3.6爬虫+Djiago2.0+Mysql --实例demo

1.切换到项目目录下&#xff0c;启动测试服务器 manage.py runserver 192.168.0.108:8888 2.设置相关配置 项目目录展示如下&#xff1a; beauty>settings.py 修改 2.1 添加app到应用程序中 2.2 设置模板路径 2.3 配置数据为mysql 2.4设置静态文件路径 2.5设置漏油 3.beau…

dubbo的invoke命令_dubbo 调试服务telnet命令

1.概述在我们使用dubbo实现分布式布局时&#xff0c;如果我们想测试我们刚写好的service层服务是否正确时&#xff0c;通常要将service层和web层同时开启&#xff0c;通过浏览器调用controller层端口&#xff0c;达到测试service层的目的。有时&#xff0c;这样的测试方法过于麻…

18个不常见的C#关键字,您使用过几个?

18个不常见的C#关键字&#xff0c;您使用过几个&#xff1f;1、__arglist 让我们先从__arglist开始。 __arglist是用来给方法传送参数。通常我们是通过函数头部指定的参数列表给方法传递参数的。如果我们想要给方法传递一组新的参数&#xff0c;我们需要重载方法。如果我们想…

C指针详解

前言:复杂类型说明 要了解指针,多多少少会出现一些比较复杂的类型,所以我先介绍一下如何完全理解一个复杂类型,要理解复杂类型其实很简单,一个类型里会出现很多运算符,他们也像普通的表达式一样,有优先级,其优先级和运算优先级一样,所以我总结了一下其原则:从变量名处起,根据运…

java collection api_Java Stream和Collection比较:何时以及如何从Java API返回?

向您展示一些可以非常方便地使用Java Stream流的场景以及如何使用它们的示例。本文基于标准Java库java.util.stream。它既与反应流无关&#xff0c;也与诸如Vavr之类的其他流实现无关。另外&#xff0c;我将不介绍诸如并行执行之类的流的高级细节。首先&#xff0c;让我们简要讨…

依赖属性

项目的WF中用到了依赖属性, 有点晕, 不明白, 先来段代码: public static DependencyProperty IsSignInProperty DependencyProperty.Register("IsSignIn", typeof(System.String), typeof(StateMachineWF.WF1)); [DesignerSerializationVisibilityAttribute(Designe…

[UE4]集合:TSet容器

一、TSet<T>是什么 UE4中&#xff0c;除了TArray动态数组外&#xff0c;还提供了各种各样的模板容器。这一节&#xff0c;我们就介绍集合容器——TSet<T>。类似于TArray<T>&#xff0c;尖括号里面的T是模板类型&#xff0c;可以是任何C类型。一个集合表示了一…

【汇总】flash单个文件上传

之前有朋友给我发送email&#xff0c;询问我是否有单个文件上传的源代码&#xff0c;因为当时写这个好像是在09年&#xff0c;所以放哪了一时也没找着。后来整理硬盘的时候&#xff0c;找到了源码&#xff0c;所以决定来个汇总&#xff08;之前写过的关于flashjs上传文件的例子…

2018.3.24 struct

好了今天听完了struct&#xff0c;感觉也差不多了&#xff0c;后面的视频不想听了&#xff0c;io啊预处理啊什么的用时候现学就好了。主要是就这么光听却没有作业可做真的有点不爽。 明天开始15-213&#xff0c;反正手头也有c primer plus了&#xff0c;后面遇到什么问题看书就…

一直苦于没有好的资产管理软件,GLPI能解决吗?

一直苦于没有好的资产管理软件&#xff0c;正好看到网上文章有介绍glpi资产管理开源软件 在此做个记录&#xff0c;有时间一定要测试一下 &#xff08;1&#xff09;资产管理工具GLPI 官网 http://www.glpi-project.org/ GLPI是法语Gestionnaire libre de parc informatique的…

weka的java环境配置_windows下安装和配置Weka

Weka是一款免费的&#xff0c;非商业化的&#xff0c;基于java环境下的开源的机器学习以及数据挖掘软件。Weka里含有各种数据挖掘工具&#xff1a;数据预处理&#xff0c;分类与回归&#xff0c;聚类&#xff0c;关联规则和可视化工具。一、安装weka我们首先需要到weka官网上下…

Windows部署服务WDS实例

一&#xff1a;概述<?xml:namespace prefix o ns "urn:schemas-microsoft-com:office:office" />Windows&#xff08;Windows Deployment Services&#xff09; 部署服务适用与大中型网络中的计算机操作系统部署。可以使用 Windows 部署服务来管理映像以及无…

JAVA----爬虫(一)JSoup

jsoup 是一款Java 的HTML解析器&#xff0c;可直接解析某个URL地址、HTML文本内容。它提供了一套非常省力的API&#xff0c;可通过DOM&#xff0c;CSS以及类似于jQuery的操作方法来取出和操作数据。 官方api:https://jsoup.org/ 一、jsoup功能 简单的例子&#xff1a;抓取wiki的…

java语言模拟_Java语言模拟操作系统.doc

河北大学2010级操作系统课程设计论文PAGEPAGE 27装订线装订线(指导教师用表)学 生 姓 名指 导 教 师论文(设计)题目Java语言模拟操作系统主要研究(设计)内容使用java语言&#xff0c;采用多到程序设计方法基本上实现并模拟了单用户操作系统。该操作系统包括四部分内容&#xff…