C#:如何修改选定的文本/换行内容等?
我想要实现的与stackoverflow中的编辑器类似。如果我按粗体,它将用一些文本(在本例中为**)包装我选择的文本。未测试:C#:如何修改选定的文本/换行内容等?,c#,wpf,C#,Wpf,我想要实现的与stackoverflow中的编辑器类似。如果我按粗体,它将用一些文本(在本例中为**)包装我选择的文本。未测试: TextBox textBox; // ... string bolded = "**" + textBox.SelectedText + "**"; int index = textBox.SelectionStart; textBox.Text.Remove(textBox.SelectionStart, textBox.SelectionLength); tex
TextBox textBox;
// ...
string bolded = "**" + textBox.SelectedText + "**";
int index = textBox.SelectionStart;
textBox.Text.Remove(textBox.SelectionStart, textBox.SelectionLength);
textBox.Text.Insert(index, bolded);
谢谢,但是我真的不明白为什么你需要使用
e.Key&Key.B
我能不能只做e.Key==Key.Tab
?对于(Keyboard.Modifiers和ModifierKeys.Control)==ModifierKeys.Control
。。。哦,我也注意到了&
的用法,这有什么作用?但是为了进一步说明这一点,如果按下Ctrl+Shift+B(作为一个例子),我如何才能看到@jiewmeng:实际上,在这种情况下,e.Key==Key.B就可以了。&模式(按位AND)用于标志枚举。基本上,ModifierKeys枚举可以同时处于多个“状态”,因此这就是测试特定“状态”是否有效的方法@jiewmeng:要测试是否也按下了“Shift”,请将&&(Keyboard.Modifiers&ModifierKeys.Shift)=ModifierKeys.Shift)添加到条件中。
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);
}
}