WPF RichTextBox-用自定义控件替换选定的文本 [英] WPF RichTextBox - Replace Selected Text with Custom Control

查看:409
本文介绍了WPF RichTextBox-用自定义控件替换选定的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我开始使用真正粗糙的解决方案进行黑客攻击之前,我想我会看看是否有人可以在正确的方向上给我一点推动力.

Before I start hacking in a really crude solution, I thought I'd see if someone could give me a little nudge in the right direction.

我真正想做的是让用户在RichTextBox中选择一些文本,单击一个按钮,然后将这些文本转换为自定义的呈现控件.例如,将其转换为包含他们选择的文本的Button.

What I really want to do is let a user select some text in a RichTextBox, click a button, and convert that text into a custom rendered control. Convert it to a Button containing the text they had selected, for instance.

推荐答案

您可以使用Command和CommandParameter进行此操作

You can do this with Command and CommandParameter

首先,将按钮绑定到ICommand,例如:

First, bind the button to an ICommand, like:

<Button Content="Go" Command="{Binding MyCommand}" CommandParameter="{Binding ElementName=myRichTextBox, Path=Selection}" />
<RichTextBox Name="myRichTextBox" />

然后在您的ViewModel或Controller或任何位于代码后面的代码中或任何地方,将ICommand作为属性公开,并将其指向执行工作的方法,例如...

Then in your ViewModel or Controller or Code-behind or wherever, you expose the ICommand as a property,and point it to a method to do the work, like...

public ICommand MyCommand
{
    get
    {
        if (_queryCommand == null)
        {
            _queryCommand = new RelayCommand<TextSelection>(DoWork);
        }
        return _queryCommand;
    }
}

private void DoWork(TextSelection param)
{
    string selectedText = param.Text;

    // Build your control here...
    // probably put it in an ObservableCollection<Control> which is bound by an Items Control, like a ListBox
}

注意:我已经使用了Josh Smith出色的 MVVM Foundation 的RelayCommand,但是您也可以使用例如RoutedUICommand(这将使您将输入手势与命令关联起来会带来额外的好处)

Note: I have used the RelayCommand from Josh Smith's excellent MVVM Foundation, but you could equally use a RoutedUICommand for example (which would add the extra benefit of letting you associate input gestures to your command)

这篇关于WPF RichTextBox-用自定义控件替换选定的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆