在WPF(Windows Presentation Foundation)中实现图文混排显示可以通过多种方式来完成。这里介绍一种常见的方法,使用 FlowDocument 和 RichTextBox 控件。

步骤概述:
- 创建WPF项目:在Visual Studio中创建一个新的WPF应用程序项目。
- 设计UI:在主窗口 (MainWindow.xaml) 中添加 RichTextBox 控件。这个控件可以支持文本和图像的混排。
- 使用FlowDocument:RichTextBox 控件中的内容是通过 FlowDocument 来管理的。你可以向 FlowDocument 添加 Paragraph,在其中可以混合使用文本(Run)和图像(Image)。
- 加载和显示图像:可以使用 BitmapImage 类来加载图像,并将其作为 Image 控件的源,然后将这个 Image 控件添加到 FlowDocument 中。
示例代码:
MainWindow.xaml
<Window x:Class="WpfApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Title1" Height="450" Width="800">
<Grid>
<RichTextBox x:Name="chatBox" />
</Grid>
</Window>
MainWindow.xaml.cs
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApp
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
AddTextAndImage("Hello, this is a text message.", "test.png",20,20);
}
private void AddTextAndImage(string text, string imagePath, int imageWidth, int imageHeight)
{
Paragraph paragraph = new Paragraph();
paragraph.Inlines.Add(new Run(text));
Image image = new Image();
BitmapImage bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.UriSource = new Uri(imagePath, UriKind.Relative);
bitmap.EndInit();
image.Source = bitmap;
image.Width = imageWidth; // 设置图片的宽度
image.Height = imageHeight; // 设置图片的高度
image.Stretch = Stretch.Uniform; // 保持图片的宽高比
paragraph.Inlines.Add(image);
chatBox.Document.Blocks.Add(paragraph);
}
}
}
注意:
- 需要替换 "test.png" 为你的图片路径。
- 根据需要调整窗口和控件的属性(如大小、样式等)。