Все ответы здесь - просто использование TextBoxили попытка осуществить выделение текста вручную, что приводит к низкой производительности или нестандартному поведению (мигание каретки TextBox, отсутствие поддержки клавиатуры в ручных реализациях и т. Д.)
После нескольких часов копания и чтения исходного кода WPF , я вместо этого обнаружил способ включения встроенного выделения текста WPF для TextBlockэлементов управления (или вообще любых других элементов управления). Большая часть функциональности вокруг выделения текста реализована в System.Windows.Documents.TextEditorсистемном классе.
Чтобы включить выделение текста для вашего контроля, вам нужно сделать две вещи:
Вызовите TextEditor.RegisterCommandHandlers()один раз, чтобы зарегистрировать обработчики событий класса
Создание экземпляра TextEditorдля каждого экземпляра вашего класса и передать основной экземпляр ваших System.Windows.Documents.ITextContainerк нему
Также существует требование, чтобы Focusableсвойство вашего элемента управления было установлено на True.
Это оно! Звучит просто, но, к сожалению, TextEditorкласс помечен как внутренний. Поэтому мне пришлось написать обертку для отражения:
class TextEditorWrapper
{
private static readonly Type TextEditorType = Type.GetType("System.Windows.Documents.TextEditor, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");
private static readonly PropertyInfo IsReadOnlyProp = TextEditorType.GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
private static readonly PropertyInfo TextViewProp = TextEditorType.GetProperty("TextView", BindingFlags.Instance | BindingFlags.NonPublic);
private static readonly MethodInfo RegisterMethod = TextEditorType.GetMethod("RegisterCommandHandlers",
BindingFlags.Static | BindingFlags.NonPublic, null, new[] { typeof(Type), typeof(bool), typeof(bool), typeof(bool) }, null);
private static readonly Type TextContainerType = Type.GetType("System.Windows.Documents.ITextContainer, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");
private static readonly PropertyInfo TextContainerTextViewProp = TextContainerType.GetProperty("TextView");
private static readonly PropertyInfo TextContainerProp = typeof(TextBlock).GetProperty("TextContainer", BindingFlags.Instance | BindingFlags.NonPublic);
public static void RegisterCommandHandlers(Type controlType, bool acceptsRichContent, bool readOnly, bool registerEventListeners)
{
RegisterMethod.Invoke(null, new object[] { controlType, acceptsRichContent, readOnly, registerEventListeners });
}
public static TextEditorWrapper CreateFor(TextBlock tb)
{
var textContainer = TextContainerProp.GetValue(tb);
var editor = new TextEditorWrapper(textContainer, tb, false);
IsReadOnlyProp.SetValue(editor._editor, true);
TextViewProp.SetValue(editor._editor, TextContainerTextViewProp.GetValue(textContainer));
return editor;
}
private readonly object _editor;
public TextEditorWrapper(object textContainer, FrameworkElement uiScope, bool isUndoEnabled)
{
_editor = Activator.CreateInstance(TextEditorType, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.CreateInstance,
null, new[] { textContainer, uiScope, isUndoEnabled }, null);
}
}
Я также создал SelectableTextBlockпроизводную от того, TextBlockчто предпринимает шаги, отмеченные выше:
public class SelectableTextBlock : TextBlock
{
static SelectableTextBlock()
{
FocusableProperty.OverrideMetadata(typeof(SelectableTextBlock), new FrameworkPropertyMetadata(true));
TextEditorWrapper.RegisterCommandHandlers(typeof(SelectableTextBlock), true, true, true);
// remove the focus rectangle around the control
FocusVisualStyleProperty.OverrideMetadata(typeof(SelectableTextBlock), new FrameworkPropertyMetadata((object)null));
}
private readonly TextEditorWrapper _editor;
public SelectableTextBlock()
{
_editor = TextEditorWrapper.CreateFor(this);
}
}
Другой вариант - создать прикрепленное свойство, TextBlockчтобы включить выбор текста по требованию. В этом случае, чтобы снова отключить выделение, нужно отсоединить a TextEditor, используя эквивалент отражения этого кода:
_editor.TextContainer.TextView = null;
_editor.OnDetach();
_editor = null;