I have a RichTextBox
that has to contain some buttons which should be deleted properly (handled) when the user is editing content in it. I am able to check if I'm deleting (Backspace, Delete or Cut) text (characters) but not the <Button>
control element.
Attached is the code I've used:
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
}
and the event:
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; */
}
}
I understand that the start.GetTextInRun
only gets the text, and I get the value "" (null
) when backspacing a button. But I've tried start.GetAdjacentElement
as well but I'm unable to succeed to retrieve a <Button>
in the same condition.