WPF RichTextBox - Replace Selected Text with Custom Control

女生的网名这么多〃 提交于 2019-12-13 16:29:13

问题


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.

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.


回答1:


You can do this with Command and CommandParameter

First, bind the button to an ICommand, like:

<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 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
}

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)




回答2:


You'll need to write some code that takes your selection and wraps it in an InlineUIContainer - that's how you get 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>


来源:https://stackoverflow.com/questions/1338951/wpf-richtextbox-replace-selected-text-with-custom-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!