Все ответы здесь - это просто использование 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
, чтобы включить выбор текста по запросу. В этом случае, чтобы снова отключить выделение, необходимо отсоединить TextEditor
, используя эквивалент отражения этого кода:
_editor.TextContainer.TextView = null;
_editor.OnDetach();
_editor = null;