我有一个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>
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)
和事件:
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); …
Run Code Online (Sandbox Code Playgroud)