使用撤消和重做命令更改 RichTextBox 工具栏颜色

Change RichTextBox ToolBar Color with Undo and Redo Command

1- 运行 以下代码。

<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">

<StackPanel>
    <ToolBar>
        <Button x:Name="UndoButton" Width="30" CommandTarget="{Binding ElementName=RichTextBox1}" Command="ApplicationCommands.Undo">
            <TextBlock x:Name="UndoTextBlock" Foreground="Gray" FontFamily="Wingdings 3" FontSize="24" Text="Q"/>
        </Button>

        <Button x:Name="RedoButton" Width="30" CommandTarget="{Binding ElementName=RichTextBox1}" Command="ApplicationCommands.Redo">
            <TextBlock x:Name="RedoTextBlock" Foreground="Gray" FontFamily="Wingdings 3" FontSize="24" Text="P"/>
        </Button>
    </ToolBar>

    <RichTextBox x:Name="RichTextBox1">
        <FlowDocument>
            <Paragraph>
                <Run Text="Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."/>
            </Paragraph>
        </FlowDocument>
    </RichTextBox>
</StackPanel>

</Window> 

2- 检查将鼠标放在 UndoButton 上时 UndoButton 是否突出显示。

3- 从开头 window.

中删除一些文本

4- 检查当您将鼠标放在 UndoButton 上时 UndoButton 是否突出显示。

5- 如您所见,如果您删除了一些文本,那么当您将鼠标放在 UndoButton 上时,UndoButton 会突出显示

我的问题在这里;

我想在用户删除一些文本时(当 UndoButton 处于活动状态时)将 UndoTextBlock 的前景色从 灰色 更改为 绿色

我认为可以处理 RichTextBox1 的 TextChanged 事件。

首先,从RichTextBox中获取原始内容。

然后,将原始内容与新内容进行比较。

如果内容已更改,请将 undoTextBlock 的前景颜色更改为绿色。

    private void RichTextBox1_OnTextChanged(object sender, TextChangedEventArgs e)
    {
        var textRange = new TextRange(RichTextBox1.Document.ContentStart,RichTextBox1.Document.ContentEnd);
        var text = textRange.Text;

        if (string.IsNullOrEmpty(text.Trim()))
            return;

        if (!_loaded)
        {
            _orginalContent = text;
            _loaded = true;
        }

        var newContent = text;
        if (newContent == _orginalContent)
            UndoTextBlock.Foreground = Brushes.Gray;
        else
            UndoTextBlock.Foreground = Brushes.Green;
    }