[英]Prevent delete/backspace of InlineUIContainers in RichTextBox (WPF)
[英]How to check if I'm deleting (Backspace, Delete or 'Cut') a UIElement in a RichTextBox?
我有一個RichTextBox
必須包含一些按鈕,當用戶在其中編輯內容時應該正確刪除(處理)這些按鈕。 我能夠檢查我是否正在刪除(Backspace、Delete 或 Cut)文本(字符),但不是<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>
。
我剛剛(大致)復制了上面的代碼,當我將 cursor 放在添加的按鈕之后並按 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;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.