繁体   English   中英

windows forms RichTextBox 控件中不显示所选文本

[英]Selected text is not displayed in windows forms RichTextBox control in a WPF window

出于某种原因,我必须使用 Windows.Forms。 我的 WPF Window 中的RichTextBox控件:

<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 中的 select 文本:

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

消息框正确显示选定的文本,但在显示的RichTextBox控件中没有突出显示。 编辑:使用鼠标或键盘时,选择工作得很好。

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

有人对此有任何线索吗?

选择有效,但 RichTextBox 没有焦点。 您可以通过rtb.Focus(); 在通过 Tab 键手动选择或聚焦控件后。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM