问题
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?
回答1:
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:
- Create a class that inherits from ContentControl
- Expose a new dependency properties of type DataTemplate: one called EditableTemplate.
- Add a MouseLeftButtonUp event handler inside your OnApplyTemplate to listen for the click.
- Change the active content template to be your EditableTemplate on the click event.
- Change the template back when the control loses focus.
Now to use your custom control inside TreeView:
- Override your ItemTemplate for your TreeView
- 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.
来源:https://stackoverflow.com/questions/831796/click-to-edit-in-silverlight