tags:

views:

68

answers:

2

what i want to acheive is similar to the editor in stackoverflow. where if i press bold, it will wrap my selected text with some text (in this case **)

+1  A: 

Not tested:

TextBox textBox;
// ...
string bolded = "**" + textBox.SelectedText + "**";
int index = textBox.SelectionStart;
textBox.Text.Remove(textBox.SelectionStart, textBox.SelectionLength);
textBox.Text.Insert(index, bolded);
thelost
+2  A: 
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); 
    }
}
Ani
jiewmeng
Ani
Ani