views:

366

answers:

1

Is there a way to make a "click-to-edit" control in silverlight? I've got some items that will be displayed in a treeview control, and I would like the labels to be editable directly in the treeview.

Anyone know how to do this?

+5  A: 

Very easy actually. I have implemented many forms with such a swapping mechanism.

You could do this using a Converter and do a simple BooleanToVisibility conversion on an IsEditable property that exists on the entities that you bind to your TreeView. Within your TreeView ItemTemplate just bind the TextBlock in such a way that it is Collapsed whenever the IsEditable property is true and bind the TextBox in such a way that it is collapesed when IsEditable property is false (and vice versa).

If you wanted to build a custom ClickToEdit control you would need to do the following:

  1. Create a class that inherits from ContentControl
  2. Expose a new dependency properties of type DataTemplate: one called EditableTemplate.
  3. Add a MouseLeftButtonUp event handler inside your OnApplyTemplate to listen for the click.
  4. Change the active content template to be your EditableTemplate on the click event.
  5. Change the template back when the control loses focus.

Now to use your custom control inside TreeView:

  1. Override your ItemTemplate for your TreeView
  2. Put your custom ClickToEdit control inside there

Implementing a custom control would allow you (or other developers) to easily specify what control they wanted to use as the content editor. For example, they could specify a NumericUpDown or a DateTimePicker instead of just using a TextBox.

Check out DataForm in Silverlight 3. It has similar functionality but the switching of the editable vs. read-only is not done by a click.

markti
Great answer, thanks!
Ben Collins