0

こんにちは私はWPFで作業していて、MVVMパターンを使用しています。したがって、私の問題は、RichTextBoxの選択されたテキストをViewModelのプロパティにバインドしようとしていますが、Selectionプロパティをバインドできないことです。

では、どうすればそれができますか?

RichTextBoxのSelectionプロパティをViewModelのプロパティにバインドすることは、テキストに効果や装飾を適用する方が良いと思う方法です。

誰かがViewModelでRichTextBoxの選択されたテキストを知るためのより良い方法を知っているなら、私に知らせてください。私はFlowDocumentsについて学び始め、RichTextBoxを操作しているので、少し迷っています。

前もって感謝します!

4

1 に答える 1

3

あなたは使用することができます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>

SelectedTextViewModelの文字列プロパティはどこにありますか)

于 2012-04-18T23:23:33.063 に答える