C#:我如何修改选定的文本/包装内容等?

时间:2010-08-23 12:56:41

标签: c# wpf

我想要实现的类似于stackoverflow中的编辑器。如果我按下粗体,它将用一些文本(在这种情况下**)包装我选择的文本

2 个答案:

答案 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);