我想要实现的类似于stackoverflow中的编辑器。如果我按下粗体,它将用一些文本(在这种情况下**)包装我选择的文本
答案 0 :(得分:2)
public Window1()
{
InitializeComponent();
textBox.KeyDown += OnTextBoxKeyDown;
}
private void OnTextBoxKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.B
&& (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
{
string boldText = "**";
int beginMarkerIndex = textBox.SelectionStart;
int endMarkerIndex = beginMarkerIndex + textBox.SelectionLength + boldText.Length;
textBox.Text = textBox.Text.Insert(beginMarkerIndex, boldText)
.Insert(endMarkerIndex, boldText);
}
}
答案 1 :(得分:0)
未经测试:
TextBox textBox;
// ...
string bolded = "**" + textBox.SelectedText + "**";
int index = textBox.SelectionStart;
textBox.Text.Remove(textBox.SelectionStart, textBox.SelectionLength);
textBox.Text.Insert(index, bolded);