Silverlight Click to Edit TextBlock

By March 15, 2012Silverlight

There are some powerful data editing controls in Silverlight such as the DataForm which let you define templates for ReadOnly and Edit modes, but sometimes you just need a simple way to view and update text.  I came across a scenario in a custom application that required a simple way to view and edit text.  The solution I came up with was a “Click to Edit” TextBlock.  In the default state, the text is displayed as a read-only TextBlock, but you can simply click on the TextBlock for it to become an editable TextBox.

Here is a working example (Silverlight 5 plugin required):

Get Microsoft Silverlight

To accomplish this, I built a UserControl that has both a TextBlock and a TextBox which are both bound to the same DependencyProperty for the Text value. Then I bind the visibility of each to an IsEditing DependencyProperty that gets toggled based on the focus state of the control.

<TextBlock Name="TextBlock" Width="150" HorizontalAlignment="Left" Text="{Binding Text, Mode=OneWay}" VerticalAlignment="Center" Visibility="{Binding IsEditing, Converter={StaticResource invisibilityConverter}}"/>
<TextBox Name="TextBox" Width="150" HorizontalAlignment="Left" Text="{Binding Text, Mode=TwoWay}" VerticalAlignment="Center" Visibility="{Binding IsEditing, Converter={StaticResource visibilityConverter}}" LostFocus="TextBox_LostFocus"/>

Once this control is in place, using it is quite simple and you can bind the Text property as needed.

    <Controls:ClickToEditTextBlock Text="{Binding Text1, Mode=TwoWay}"/>
    <Controls:ClickToEditTextBlock Text="{Binding Text2, Mode=TwoWay}"/>
    <Controls:ClickToEditTextBlock Text="{Binding Text3, Mode=TwoWay}"/>

Download the Source Code

The following two tabs change content below.

Josh Eastburn

Senior Software Architect at Falafel Software Inc
Josh has over 15 years of web and application development experience as a software architect and consultant in various industries including distribution, logistics, financial services, transportation, and education. He enjoys working with the latest technologies and specializes in using C#, ASP.NET MVC, JavaScript, HTML5, CSS, XAML, and SQL Server to deliver enterprise-scale applications. He is a Microsoft Certified Technology Specialist and a Telerik Kendo UI Certified Developer. Josh holds a BS in Computer Science and Business Systems from Taylor University and lives in Charlotte, NC. He enjoys traveling and spending time outdoors with his wife and children.

Latest posts by Josh Eastburn (see all)