将RichTExtBox放在UserControl中,并使用以下代码:
// SelectedText property.
public static readonly DependencyProperty SelectedTextProperty =
DependencyProperty.Register("SelectedText", typeof(TextSelection),
typeof(MyRichTextBox ));
/// <summary>
/// Default constructor.
/// </summary>
public MyRichTextBox ()
{
InitializeComponent();
this.TextBox.SelectionChanged += new RoutedEventHandler(TextBox_SelectionChanged);
}
void TextBox_SelectionChanged(object sender, RoutedEventArgs e)
{
var sT = (e.OriginalSource as RichTextBox).Selection;
SelectedText = sT;
}
/// <summary>
/// The WPF Selected Text of the FlowDocument in the control
/// </summary>
public TextSelection SelectedText
{
get { return (TextSelection)GetValue(SelectedTextProperty); }
set { SetValue(SelectedTextProperty, value); }
}
//UserControl embedded in the MainWindow.xaml
<My:MyRichTextBox SelectedText="{Binding SelectedDocument,Mode=TwoWay}" x:Name="EditBox" />
现在您可以访问ViewModel中richtextbox的TextSelection了!