如何检查我是否在RichTextBox中删除(退格,删除或“剪切”)UIElement?

时间:2011-07-14 09:13:06

标签: c# wpf richtextbox uielement

我有一个RichTextBox,必须包含一些按钮,当用户编辑其中的内容时,这些按钮应该被正确删除(处理)。我可以检查是否删除(退格,删除或剪切)文本(字符)但不删除<Button>控件元素。

附件是我用过的代码:

XAML:

<RichTextBox x:Name="tRTB"
             HorizontalAlignment="Left"
             Keyboard.PreviewKeyDown="tRTB_PreviewKeyDown"
             PreviewTextInput="tRTB_PreviewTextInput">
   <local:EnabledFlowDocument x:Name="tFD">
      <Paragraph x:Name="tP"/>                 
   </local:EnabledFlowDocument>
</RichTextBox>

C#:

public void AppendNewButton(int i)
{
    Button addB = new Button();
    addB.Content = i;
    addB.HorizontalAlignment = HorizontalAlignment.Left;

    tP.Inlines.Add(addB);
    tP.Inlines.Add("Bk" + i.ToString()); //appends a button and text in RTB
}

和事件:

private void tRTB_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Back)
    {
        var start = tRTB.CaretPosition;
        var t = start.GetTextInRun(LogicalDirection.Backward);
        var end = start.GetNextContextPosition(LogicalDirection.Backward);
        var t1 = end.GetTextInRun(LogicalDirection.Backward);

        tRTB.Selection.Select(start, end);
        tRTB.Selection.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Black);
        tRTB.Selection.Select(start, start);

        //should handle deletion of button here
        /* if (button is before cursor) */
        /* e.Handled=true; */
    }
}

我知道start.GetTextInRun只获取文本,并且在退回按钮时获得值“”(null)。但我也试过了start.GetAdjacentElement,但我无法成功检索到同一条件下的<Button>

1 个答案:

答案 0 :(得分:-1)

我刚刚(大致)复制了你的代码,当我把光标放在添加的按钮之后并按下Backspace时,即使没有你的PreviewKeyDown代码,按钮也会从RichTextBox中删除。所以我很困惑,因为似乎答案只是你根本不需要做任何事情。这是我的代码:

<Window x:Class="WpfApplication4.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">
  <Grid>
    <RichTextBox 
      x:Name="tRTB"
      HorizontalAlignment="Left"
      Keyboard.PreviewKeyDown="tRTB_PreviewKeyDown">
    </RichTextBox>
  </Grid>
</Window>

和背后的代码......

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    public void AppendNewButton(int i)
    {
        Button addB = new Button();
        addB.Content = i;
        addB.HorizontalAlignment = HorizontalAlignment.Left;

        var insertionPosition = tRTB.CaretPosition.GetInsertionPosition(LogicalDirection.Forward);

        var inline = new InlineUIContainer(addB);
        insertionPosition.Paragraph.Inlines.InsertAfter(
            (Inline)insertionPosition.Parent,
            inline);

        tRTB.CaretPosition = tRTB.CaretPosition.GetNextInsertionPosition(LogicalDirection.Forward);
    }

    public void tRTB_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.B)
        {
            AppendNewButton(7);
            e.Handled = true;
        }
    }
}