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

时间:2019-03-28 20:09:50

标签: c# wpf vb.net xaml 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-从打开的窗口中删除一些文本。

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

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

我的问题在这里;

当用户删除某些文本时(当“撤消按钮”处于活动状态时),我想将UndoTextBlock的前景颜色从灰色更改为绿色

1 个答案:

答案 0 :(得分:0)

我认为可以处理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;
    }

enter image description here