C# 所选文本不会显示在WPF窗口的windows窗体RichTextBox控件中

C# 所选文本不会显示在WPF窗口的windows窗体RichTextBox控件中,c#,.net,wpf,winforms-interop,C#,.net,Wpf,Winforms Interop,由于某些原因,我不得不使用Windows.Forms。“我的WPF”窗口中的控件: <Window x:Class="TestSelectionRTBDansWPF.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d

由于某些原因,我不得不使用Windows.Forms。“我的WPF”窗口中的控件:

<Window x:Class="TestSelectionRTBDansWPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
        xmlns:local="clr-namespace:TestSelectionRTBDansWPF"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid Margin="10">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Button x:Name="btnSelect" Content="Select 10 first characters" Padding="10" Margin="0 0 0 10" Width="160" Click="BtnSelect_Click"/>
        <WindowsFormsHost Grid.Row="1">
            <wf:RichTextBox x:Name="rtb" Dock="Fill" Text="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis non mauris id ipsum auctor vehicula sed ut felis. Donec porttitor nisi eget ex porttitor, sed posuere sapien pretium."/>
        </WindowsFormsHost>
    </Grid>
</Window>

消息框正确显示所选文本,但在显示的
RichTextBox
控件中没有突出显示任何内容。 编辑:使用鼠标或键盘时,选择效果非常好

在写这篇文章时,我意识到添加对
System.Drawing
的引用并设置
rtb.SelectionBackColor
属性可以实现这一点,尽管它看起来更像是一个补丁,而不是一个真正的解决方案,因为我必须处理SelectionChanged以重置先前选定文本的背景色


有人对此有任何线索吗?

选择有效,但RichTextBox没有焦点。您只需通过设置RichTextBox的焦点即可
rtb.Focus()

@AlexF如果我删除对
MessageBox.Show的调用,则不会发生任何情况。您是否尝试过“rtb.Select(Index,Length);”功能?其行为与此相同。非常感谢!我想一定是这样的,但我找不到要使用的方法,我尝试了BringToFront()和其他方法,但不记得这个方法。就这么简单!
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void BtnSelect_Click(object sender, RoutedEventArgs e)
    {
        Thread th = new Thread(() =>
        {
            Thread.Sleep(2000);
            SelectText(0, 10);
        });
        th.Start();
    }

    delegate void ParametrizedMethodInvoker5(int arg1, int arg2);
    public void SelectText(int start, int length)
    {
        if (!Dispatcher.CheckAccess())
        {
            Dispatcher.Invoke(new ParametrizedMethodInvoker5(SelectText), start, length);
            return;
        }
        rtb.SelectionStart = start;
        rtb.SelectionLength = length;
        MessageBox.Show("Selection done!\nSelected text: " + rtb.SelectedText);
    }
}