tags:

views:

46

answers:

2

How can I from a ViewModel, find out what is the selected text? What I am doing wanting to accomplish is similar to the WMD Markdown Editor here on StackOverflow when you bold/format text. Work on the selected text and modify it

+1  A: 

Hi!

Doesn't seem right for you to manage the selection in the ViewModel, that should not contain functionality, only business data. But in any case:

Bind the SelectionChanged event for the textbox:

<TextBox SelectionChanged="TextBox_SelectionChanged"/>

And then handle the selection in whatever way you find pleasant:

private void TextBox_SelectionChanged(object sender, RoutedEventArgs e)
{
    string thisIsTheSelectedText = ((TextBox) sender).SelectedText;
}

Or bind it twoway to a property on the ViewModel:

<TextBox SelectedText="{Binding MyModelProperty, Mode=TwoWay}"/>
Almund
I decided to encapsulate such functionality into a user control + `RoutedCommands`, it think it should be better.
jiewmeng
A: 
you can create a property in your viewmodel and bind to the SelectedText property in a MVVM way.

<TextBox SelectedText="{Binding MyModelProperty, Mode=TwoWay}"/> 
saurabh