思路如下
- 模板中同时存在只显示文本的Textblock和编辑的TextBox;
- 控件有显示和编辑两种状态,默认为显示状态,双击进入编辑状态;
- 点击时记录状态,第二次点击时显示TextBox以实现进行编辑功能;
代码实现
XAML代码
<Style TargetType="{x:Type local:TextEditable}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:TextEditable}">
<Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}">
<Grid>
<TextBlock x:Name="PART_TextBlock"
Background="Transparent"
FontSize="{Binding FontSize, Mode=TwoWay, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=local:TextEditable}}"
Text="{Binding Text, Mode=TwoWay, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=local:TextEditable}}" />
<TextBox x:Name="PART_TextBox"
Margin="-2,0,0,0"
BorderThickness="0"
Background="Transparent"
Visibility="Collapsed"
FontSize="{Binding FontSize, Mode=TwoWay, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=local:TextEditable}}"
Text="{Binding Text, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=local:TextEditable}}" />
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
C#代码
[TemplatePart(Name = "PART_TextBlock", Type = typeof(TextEditable))]
[TemplatePart(Name = "PART_TextBox", Type = typeof(TextEditable))]
public class TextEditable : Control
{
public TextEditable()
{
MouseLeftButtonDown += TextEditable_MouseLeftButtonDown;
LostFocus += TextEditable_LostFocus;
}
private void TextEditable_LostFocus(object sender, RoutedEventArgs e)
{
isSelected = false;
Background = Brushes.Transparent;
box.Visibility = Visibility.Collapsed;
block.Visibility = Visibility.Visible;
}
bool isSelected = false;
private void TextEditable_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (!isSelected)
{
isSelected = true;
box.Focus();
}
else
{
box.Visibility = Visibility.Visible;
block.Visibility = Visibility.Collapsed;
box.Focus();
box.SelectAll();
}
}
static TextEditable()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(TextEditable), new FrameworkPropertyMetadata(typeof(TextEditable)));
}
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(TextEditable), new PropertyMetadata(string.Empty, OnTextChanged));
private static void OnTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
}
TextBlock block = null;
TextBox box = null;
public override void OnApplyTemplate()
{
block = GetTemplateChild("PART_TextBlock") as TextBlock;
box = GetTemplateChild("PART_TextBox") as TextBox;
block.LostFocus += TextEditable_LostFocus;
box.LostFocus += TextEditable_LostFocus;
}
}
效果图