对于RichTextBox控件,AppContext.SetSwitch("Switch.System.Windows.Controls.Text.UseAdornerForTextboxSelectionRendering", false); 设置不起作用的原因是该属性只适用于TextBox和PasswordBox控件,不适用于RichTextBox控件。
要在RichTextBox控件中禁用选择渲染的装饰器,可以使用以下方法:
public class MyRichTextBox : RichTextBox
{
static MyRichTextBox()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(MyRichTextBox), new FrameworkPropertyMetadata(typeof(MyRichTextBox)));
}
protected override void OnSelectionChanged(RoutedEventArgs e)
{
base.OnSelectionChanged(e);
// 移除选择渲染的装饰器
var adornerLayer = AdornerLayer.GetAdornerLayer(this);
if (adornerLayer != null)
{
var adorners = adornerLayer.GetAdorners(this);
if (adorners != null)
{
foreach (var adorner in adorners)
{
if (adorner is TextBoxSelectionAdorner)
{
adornerLayer.Remove(adorner);
}
}
}
}
}
}
通过这种方式,可以禁用RichTextBox控件中的选择渲染装饰器。