Introduction
A relatively simple but pretty clean-cut approach to making editable labels.
Background
Most solutions I found online for making editable labels in C# WPF add icons to the GUI to function with a mouse hover. I wanted one that the user can just double-click to edit, and press Enter or Tab to complete editing, and Escape to cancel editing. So I wrote this. Because of the speedbumps I hit and overcame while writing it, I thought it can help others out there avoid the same engineering issues.
Using the Code
XAML
<UserControl x:Class="EditableLabelSample.dbText"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:EditableLabelSample"
mc:Ignorable="d"
d:DesignHeight="25" d:DesignWidth="170" BorderThickness="0">
<Grid Margin="1">
<Label x:Name="lblView" Content="" VerticalAlignment="Top" Height="23"
Background="#FFD4D4D4" MouseDown="lblView_MouseDown"
MouseDoubleClick="lblView_MouseDoubleClick" VerticalContentAlignment="Center"
Margin="-3,-2,3,0"/>
<TextBox x:Name="txtEdit" Height="23" MouseUp="txtEdit_MouseUp"
TextWrapping="Wrap" VerticalAlignment="Top" KeyDown="txtEdit_KeyDown"
BorderThickness="0" UndoLimit="3" SpellCheck.IsEnabled="True"
VerticalContentAlignment="Center" OpacityMask="Lime" BorderBrush="{x:Null}"
SelectionBrush="#FF48A3FF" Background="{x:Null}"/>
</Grid>
</UserControl>
C#
private void lblView_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
lblView.Background = new SolidColorBrush(Color.FromArgb(0xFF, 0xB4, 0xFF, 0x96));
txtEdit.Visibility = Visibility.Visible;
txtEdit.AllowDrop = false;
txtEdit.Text = lblView.Content.ToString();
txtEdit.Focus();
txtEdit.IsReadOnly = false;
}
private void txtEdit_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
txtEdit.Visibility = Visibility.Hidden;
lblView.Content = txtEdit.Text;
lblView.Background = new SolidColorBrush(Color.FromArgb(0xFF, 0xD4, 0xD4, 0xD4));
}
if (e.Key == Key.Tab)
{
txtEdit.Visibility = Visibility.Hidden;
lblView.Content = txtEdit.Text;
lblView.Background = new SolidColorBrush(Color.FromArgb(0xFF, 0xD4, 0xD4, 0xD4));
}
if (e.Key == Key.Escape)
{
txtEdit.Text = lblView.Content.ToString();
txtEdit.Visibility = Visibility.Hidden;
lblView.Background = new SolidColorBrush(Color.FromArgb(0xFF, 0xD4, 0xD4, 0xD4));
}
else
{
}
}
private void lblView_MouseDown(object sender, MouseButtonEventArgs e)
{
}
private void txtEdit_MouseUp(object sender, MouseButtonEventArgs e)
{
txtEdit.Visibility = Visibility.Visible;
txtEdit.IsReadOnly = true;
}
}
}
Points of Interest
Contains code under the label's MouseDown
event that may be used to make the label contents draggable. I commented it out because it's not necessary for the given description, but can be easily implemented by removing the comments symbols.
History