[英]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.