您可以使用Behavior
:
public class RichTextSelectionBehavior : Behavior<RichTextBox>
{
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.SelectionChanged += RichTextBoxSelectionChanged;
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.SelectionChanged -= RichTextBoxSelectionChanged;
}
void RichTextBoxSelectionChanged(object sender, System.Windows.RoutedEventArgs e)
{
SelectedText = AssociatedObject.Selection.Text;
}
public string SelectedText
{
get { return (string)GetValue(SelectedTextProperty); }
set { SetValue(SelectedTextProperty, value); }
}
public static readonly DependencyProperty SelectedTextProperty =
DependencyProperty.Register(
"SelectedText",
typeof(string),
typeof(RichTextSelectionBehavior),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnSelectedTextChanged));
private static void OnSelectedTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var behavior = d as RichTextSelectionBehavior;
if (behavior == null)
return;
behavior.AssociatedObject.Selection.Text = behavior.SelectedText;
}
}
XAML 用法:
<RichTextBox>
<i:Interaction.Behaviors>
<local:RichTextSelectionBehavior SelectedText="{Binding SelectedText}" />
</i:Interaction.Behaviors>
</RichTextBox>
(SelectedText
ViewModel 上的字符串属性在哪里)