将 RichTextBox 的选定文本绑定到 ViewModel 中的属性

Mig*_*uel 2 data-binding wpf richtextbox wpf-controls flowdocument

您好,我正在使用 WPF 并使用 MVVM 模式。所以我的问题是,我试图将 RichTextBox 的选定文本绑定到 ViewModel 中的属性,但无法绑定 Selection 属性。

那么我该怎么做呢?

我认为将 RichTextBox 的 Selection 属性绑定到 ViewModel 中的属性是更好地将效果和装饰应用于文本的方法。

如果有人知道更好的方法来了解 ViewModel 中 RichTextBox 的选定文本,请告诉我。我开始学习 FlowDocuments 并使用 RichTextBox,所以这就是我有点迷失的原因。

提前致谢!

Tho*_*que 5

你可以使用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;
    }
}
Run Code Online (Sandbox Code Playgroud)

XAML 用法:

    <RichTextBox>
        <i:Interaction.Behaviors>
            <local:RichTextSelectionBehavior SelectedText="{Binding SelectedText}" />
        </i:Interaction.Behaviors>
    </RichTextBox>
Run Code Online (Sandbox Code Playgroud)

SelectedTextViewModel 上的字符串属性在哪里)