WPF 中的可编辑文本块
在 WPF 中创建可编辑的文本块。
引言
许多应用程序需要具备双击文本块时进行编辑的功能。这种功能常见于树形节点中,例如 Windows 资源管理器树。因此,我决定创建一个控件,允许用户通过双击或使用功能键 F2 来编辑文本块。
背景
本文使用 Adorner 在编辑模式下显示文本框。
Using the Code
EditableTextBlock
继承自 TextBlock
(System.Windows.Controls.TextBlock
),以提供编辑功能。
类图如下所示

EditableTextBlock
是可以直接使用的控件,用于创建可编辑的文本块。该控件具有以下依赖属性,通过这些属性可以使用编辑功能。
属性
IsInEditMode
是一个布尔属性,顾名思义,当设置为true
时启用编辑模式,而false
则退出编辑模式。MaxLength
是一个整数,用于设置在控件处于编辑模式时显示的textbox
的MaxLength
。
另一个类 EditableTextBlockAdorner
是一个 Adorner
,包含在 EditableTextBlock
处于编辑模式时显示的文本框。
Adorner
是可以添加到另一个 UIElement
的 Adorner Layer 的元素。
它还允许您扩展控件的功能,EditableTextBlock
利用这一点来提供编辑功能。
有关 Adorners
的更多详细信息,请参阅 此链接。
EditableTextBlock
代码
当依赖属性 IsInEditMode
的值发生变化时的回调方法
private static void IsInEditModeUpdate
(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
EditableTextBlock textBlock = obj as EditableTextBlock;
if (null != textBlock)
{
//Get the adorner layer of the uielement (here TextBlock)
AdornerLayer layer = AdornerLayer.GetAdornerLayer(textBlock);
//If the IsInEditMode set to true means the user has enabled the edit mode then
//add the adorner to the adorner layer of the TextBlock.
if (textBlock.IsInEditMode)
{
if (null == textBlock._adorner)
{
textBlock._adorner = new EditableTextBlockAdorner(textBlock);
//Events wired to exit edit mode when the user presses
//Enter key or leaves the control.
textBlock._adorner.TextBoxKeyUp += textBlock.TextBoxKeyUp;
textBlock._adorner.TextBoxLostFocus += textBlock.TextBoxLostFocus;
}
layer.Add(textBlock._adorner);
}
else
{
//Remove the adorner from the adorner layer.
Adorner[] adorners = layer.GetAdorners(textBlock);
if (adorners != null)
{
foreach (Adorner adorner in adorners)
{
if (adorner is EditableTextBlockAdorner)
{
layer.Remove(adorner);
}
}
}
//Update the textblock's text binding.
BindingExpression expression = textBlock.GetBindingExpression(TextProperty);
if (null != expression)
{
expression.UpdateTarget();
}
}
}
}
使用 EditableTextBlock
<TreeView x:Name="tree" .. ItemsSource="{Binding PersonCollection}">
<TreeView.Resources>
<HierarchicalDataTemplate ..>
<local:EditableTextBlock Text="{Binding Name, Mode=TwoWay}"
IsInEditMode="{Binding Edit, Mode=TwoWay}"/>
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>
注意:如果文本与绑定有关,则绑定的模式必须为 TwoWay
,以便控件可以在编辑文本框中编辑值时更新绑定源。
历史
- 2010 年 4 月 - 初始版本