You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF RichTextBox加粗按钮问题:设置加粗后选区消失

WPF RichTextBox 加粗操作后选区丢失问题

需求:使用WPF的RichTextBox实现以下功能:选中文本后点击加粗按钮,文本变为粗体但选区保持不变;再次点击按钮取消粗体,选区仍保留。但实际操作中,点击加粗按钮后选区会消失。

XAML代码

<Window x:Class="WpfApp2.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:local="clr-namespace:WpfApp2"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <DockPanel>
        <StackPanel Orientation="Horizontal" DockPanel.Dock="Top">
            <Button Name="Bold" Content="Bold" Click="Bold_Click"/>
        </StackPanel>
        <RichTextBox Name="RichTextBox1" />
    </DockPanel>
</Window>

C#代码

using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;
namespace WpfApp2 {    
    public partial class MainWindow : Window {
        public MainWindow() {
            InitializeComponent();
            RichTextBox1.CaretPosition.InsertTextInRun("Select this text with a mouse click-and-drag, " 
                                                       + "then click bold button, and observe that "
                                                       + "selection highlight disappears");
        }
        private bool SelectionIsBold() {
            var weight = RichTextBox1.Selection.GetPropertyValue(FontWeightProperty);
            var unset = DependencyProperty.UnsetValue;
            var SelectionIsBold = weight != unset && (FontWeight)weight == FontWeights.Bold;
            return SelectionIsBold;
        }
        private void Bold_Click(object sender, RoutedEventArgs e) {
            if (RichTextBox1.Selection.IsEmpty) return;
            var textRange = RichTextBox1.Selection;
            var len = RichTextBox1.Selection.Text.Length;
            var startpos = RichTextBox1.CaretPosition.GetPositionAtOffset(0);
            var endpos = RichTextBox1.CaretPosition.GetPositionAtOffset(len);  //GetPoint(start, len);
            if (SelectionIsBold())
                RichTextBox1.Selection.ApplyPropertyValue(Inline.FontWeightProperty, FontWeights.Normal);
            else
                RichTextBox1.Selection.ApplyPropertyValue(Inline.FontWeightProperty, FontWeights.Bold);

            // ==>> DOESN'T WORK: Attempt to Reselect Text After ApplyPropertyValue because it unhighlights the selection...
            RichTextBox1.SelectionBrush = new SolidColorBrush(Colors.Red);
            RichTextBox1.Selection.Select(startpos, endpos);
        }
    } // class
} // namespace

内容的提问来源于stack exchange,提问作者Bill Moore

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 01:06:39