WPF RichTextBox - Replace selected text with custom control

Before starting to hack into a really crude solution, I thought I was going to see if anyone could nudge me a little in the right direction.

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

+2


source to share


2 answers


You can do it with Command and CommandParameter

First, bind the button to ICommand, for example:

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

      



Then in your ViewModel or Controller or Code-behind or wherever you expose ICommand as a property and specify how to do this 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
}

      

Note. I used RelayCommand from Josh Smith's excellent MVVM Foundation , but you could also use RoutedUICommand for example (to add the added benefit of allowing you to associate input gestures with your command)

+2


source


You will need to write code that takes your selection and wraps it into the InlineUIContainer - how do you get the controls inside a rich text box:



<RichTextBox>
    <FlowDocument>
        <Paragraph>
            <Run>Fo</Run>
            <InlineUIContainer>
                <Button IsEnabled="True">oB</Button>
            </InlineUIContainer>
            <Run>ar</Run>
        </Paragraph>
    </FlowDocument>
</RichTextBox>

      

0


source







All Articles