当前位置: 首页 > news >正文

【WPF实现RichTextBox添加文本、自动滚动】

前言

使用WPF 中的RichTextBox控件实现添加文本后自动滚动末尾。因为RichTextBox无法直接绑定数据,所以通过引用System.Windows.Interactivity实现(System.Windows.Interactivity.WPF)

代码

MainWindow.xaml

<Window x:Class="WPF_MvvmDemo.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:behavior="clr-namespace:WPF_MvvmDemo" xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"mc:Ignorable="d"Title="MainWindow" Height="450" Width="800"><Grid><Grid.RowDefinitions><RowDefinition Height="*"/><RowDefinition Height="50"/></Grid.RowDefinitions><RichTextBox Name="OutputListBox" Grid.Row="0"  Margin="5" Background="#FFFFFF" Focusable="True" VerticalScrollBarVisibility="Auto"><!--数据绑定--><i:Interaction.Behaviors><behavior:RichTextBoxBehavior Document="{Binding RichTextContent, Mode=TwoWay}" /></i:Interaction.Behaviors><!--自动滚动--><i:Interaction.Triggers><i:EventTrigger EventName="TextChanged"><ei:CallMethodAction MethodName="ScrollToEnd" /></i:EventTrigger></i:Interaction.Triggers></RichTextBox><Button  Grid.Row="2" Width="150" Margin="5" HorizontalAlignment="Right"Command="{Binding AppendTextCommand}">AddText</Button></Grid>
</Window>

MainWindow

public partial class MainWindow : Window
{MainViewModel viewModel;public MainWindow(){InitializeComponent();viewModel=new MainViewModel();this.DataContext = viewModel;}
}

RelayCommand

public class RelayCommand : ICommand
{public Action<string> execute;public RelayCommand(Action<string> execute){this.execute = execute;}public event EventHandler? CanExecuteChanged;public bool CanExecute(object? parameter){return CanExecuteChanged!=null;}public void Execute(object? parameter){execute?.Invoke(parameter?.ToString());}
}

RichTextBoxBehavior

/// <summary>
///RichTextBox 的 Document 属性不是一个依赖属性(DependencyProperty),因此不能直接进行双向数据绑定。
///我们需要使用一种间接的方式来实现数据绑定。
///解决方案:
///使用 Behavior 来实现 RichTextBox 的数据绑定。Behavior 是一个附加行为,可以在 XAML 中使用,
///通过代码来实现复杂的行为逻辑。
/// </summary>
public class RichTextBoxBehavior : Behavior<RichTextBox>
{public static readonly DependencyProperty DocumentProperty =DependencyProperty.Register("Document", typeof(FlowDocument), typeof(RichTextBoxBehavior),new FrameworkPropertyMetadata(null, OnDocumentChanged));public FlowDocument Document{get { return (FlowDocument)GetValue(DocumentProperty); }set { SetValue(DocumentProperty, value); }}private static void OnDocumentChanged(DependencyObject d, DependencyPropertyChangedEventArgs e){var behavior = d as RichTextBoxBehavior;if (behavior != null){behavior.UpdateRichTextBox((FlowDocument)e.NewValue);}}protected override void OnAttached(){base.OnAttached();AssociatedObject.Loaded += OnLoaded;AssociatedObject.TextChanged += OnTextChanged;}protected override void OnDetaching(){base.OnDetaching();AssociatedObject.Loaded -= OnLoaded;AssociatedObject.TextChanged -= OnTextChanged;}private void OnLoaded(object sender, RoutedEventArgs e){UpdateRichTextBox(Document);}private void OnTextChanged(object sender, TextChangedEventArgs e){Document = AssociatedObject.Document;}private void UpdateRichTextBox(FlowDocument document){if (document != null && AssociatedObject.Document != document){AssociatedObject.Document = document;}}
}

运行结果

在这里插入图片描述

http://www.lryc.cn/news/494682.html

相关文章:

  • 量化交易系统开发-实时行情自动化交易-8.4.MT4/MT5平台
  • 【HarmonyOS】@Observed和@ObjectLink嵌套对象属性更改UI不刷新问题
  • 什么是默克尔树(Merkle Tree)?如何计算默克尔根?
  • 眼部按摩仪WT2605音频蓝牙语音芯片方案 单芯片实现语音提示及控制/手机无线音频传输功能
  • python打包深度学习虚拟环境
  • springboot358智慧社区居家养老健康管理系统(论文+源码)_kaic
  • 复杂网络(二)
  • Kubernetes 01
  • node修改文件名称
  • ArcGIS 软件中路网数据的制作
  • transformers microsoft--table-transformer 表格识别
  • 【Spark源码分析】规则框架-草稿
  • 迪米特原则的理解和实践
  • jQuery零基础入门速通(中)
  • 【设计模式系列】中介者模式(十八)
  • PDF版地形图矢量出现的问题
  • 小迪安全第四十二天笔记 简单的mysql注入 mysql的基础知识 用户管理数据库模式 mysql 写入与读取 跨库查询
  • 11.25.2024刷华为OD
  • 你真的会用饼图吗?JVS-智能BI饼图组件深度解析
  • HarmonyOS Next 模拟器安装与探索
  • 医学机器学习:数据预处理、超参数调优与模型比较的实用分析
  • 单片机知识总结(完整)
  • 【C++】auto和decltype类型推导关键字
  • OGRE 3D----3. OGRE绘制自定义模型
  • ARM + Linux 开发指南
  • facebook欧洲户开户条件有哪些又有何优势?
  • 算法训练(leetcode)二刷第三十一天 | 1049. 最后一块石头的重量 II、494. 目标和、*474. 一和零
  • 软件测试丨Pytest生命周期与数据驱动
  • Figma入门-原型交互
  • 网络安全防范技术