In the fourth post in this series we’ll get to actually edit an item in the TreeView.
First, we have to make our HelpTopic class editable. Well, yes, it is editable now, but we’ll make it even more editable :) by
a] implementing the IEditableObject interface. IEditableObject is defined as:
public interface IEditableObject
{
void BeginEdit();
void CancelEdit();
void EndEdit();
}
The method names in the interface are so straightforward that I shouldn’t need to explain them here. However, one method which we benefit most from when our business object implements this interface, is CancelEdit. Why? Well, let’s say you have your TextBox twoway-bound to some object’s property. When you change the value in this TextBox and tab out, the changes are committed to your object and you have no options to undo this change. If you wanted to provide the OK/Cancel button pair for user to either confirm or undo her changes, you have a slight problem.
The IEditableObject interface is here to help. The CancelEdit method is responsible for reverting your object to the state it was before BeginEdit was called.
One of the Silverlight controls that supports this interface is DataGrid, so making your objects implement this interface will make them work consistently with DataGrid scenarios too.
Let’s see how our HelpTopic would implement the interface:
public class HelpTopic : IEditableObject
{
private string nameCopy;
public string Name { get; set; }
public ObservableCollection<HelpTopic> SubTopics { get; set; }
public HelpTopic()
{
}
public void BeginEdit()
{
nameCopy = this.Name;
}
public void CancelEdit()
{
Name = nameCopy;
}
public void EndEdit()
{
}
}
I’ve introduced a new private variable to store the value of the name property in case the CancelEdit is called. When dealing with complex objects, you would want to store a deep clone of your object instead of storing each and every (sub)property in a separate variable.
b] creating a new property, which would indicate that the object is in edit mode. We would set this property within these three new methods. It is important that changes to this property are propagated to the UI, so we also need:
c] implementing the INotifyPropertyChanged interface. This interface is not new, our PageViewModel already implements it. When implementing this interface, we can also change the Name property implementation to support notifications.
The full HelpTopic class now looks like:
public class HelpTopic : IEditableObject, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private bool isEditing;
private string name;
private string nameCopy;
public ObservableCollection<HelpTopic> SubTopics { get; set; }
public string Name
{
get { return name; }
set
{
if (name == value)
{
return;
}
name = value;
OnPropertyChanged("Name");
}
}
public bool IsEditing
{
get { return isEditing; }
private set
{
if (isEditing == value)
{
return;
}
isEditing = value;
OnPropertyChanged("IsEditing");
}
}
public HelpTopic()
{
}
public void BeginEdit()
{
nameCopy = this.Name;
IsEditing = true;
}
public void CancelEdit()
{
Name = nameCopy;
IsEditing = false;
}
public void EndEdit()
{
IsEditing = false;
}
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
[Edit: changed IsEditing setter above to private; the property should be set from within the class only]
Moving upwards to the ViewModel, we need another three commands for invoking the new methods – BeginEditTopic, EndEditTopic and CancelEditTopic commands. Their ViewModel implementation is, again, pretty simple and straightforward:
private void OnBeginEditTopic(object sender, ExecutedEventArgs e)
{
HelpTopic topic = e.Parameter as HelpTopic;
topic.BeginEdit();
}
private void OnEndEditTopic(object sender, ExecutedEventArgs e)
{
HelpTopic topic = e.Parameter as HelpTopic;
topic.EndEdit();
}
private void OnCancelEditTopic(object sender, ExecutedEventArgs e)
{
HelpTopic topic = e.Parameter as HelpTopic;
topic.CancelEdit();
}
All three methods just call their corresponding method on the HelpTopic item, passed into the method as a command parameter.
Now for the UI part… I guess I *could* do this with Xaml only, but I decided on building a new content control to pose as an View/Edit item switcher. The main reason for doing this is that I didn’t want end up with every item in the tree carry its own editor within its template. Instead, this new control will be responsible for loading the editor when one is needed.
In short, things are set up like this: I have this new control called EditableItemControl, pushed to somewhere near the top of the TreeViewItem’s visual tree with its contents set to what original item would look like. EditableItemControl has a property called EditorTemplate, which should be set to what the tree item should look like in edit mode. This is the EditorTemplate I used:
<Grid >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBox Text="{Binding Name, Mode=TwoWay}"
input:CommandService.Command="EndEditTopic"
input:CommandService.CommandParameter="{Binding}"
/>
<Button Name="saveButton" ToolTipService.ToolTip="OK" Grid.Column="1"
input:CommandService.Command="EndEditTopic"
input:CommandService.CommandParameter="{Binding}">
<Image Source="/EditableTreeView;component/Resources/ok.png" Stretch="None" />
</Button>
<Button Name="closeButton" ToolTipService.ToolTip="Cancel" Grid.Column="2"
input:CommandService.Command="CancelEditTopic"
input:CommandService.CommandParameter="{Binding}">
<Image Source="/EditableTreeView;component/Resources/cancel.png" Stretch="None" />
</Button>
</Grid>
When editing is initialized, control’s original content is preserved and replaced with the above editor template, just to be switched back when editing is over. There are two ways to commit the changes – one is to press the saveButton, and the other is to press the Return key focused on the TextBox. Note that the TextBox is also wired to the EndEditTopic command, and TextBox control being one of the actionable elements in the SLExtensions framework, this simply works.
The key to make the switch between view and edit states is EditableItem’s IsEditing dependency property – the control goes to edit state when this property is set to true, and returns to its normal state when its value is set back to false. Ok, but how is this property set? Remember that our HelpTopic class also implements a property with the same name? They fit perfectly together:
<local:EditableTreeViewItem Grid.ColumnSpan="3"
IsEditing="{Binding IsEditing}"
HorizontalContentAlignment="Stretch">
...
</local:EditableTreeViewItem>
To tie all the ends together – when the Edit button is pressed, BeginEdit command is executed. ViewModel handles that command by calling the BeginEdit method on the HelpTopic item, for which the command was executed. IsEditing property gets set for this item and at the same time picked up by the EditableItemControl, which does the switch and display the editor for it. It’s like playing The Incredible Machine!
OK, we made the TreeView control editable. However, there are a few visual issues – one of them is that a mouse-over in a subitem shows the edit/delete commands for its ancestors all the way up to the root. I don’t know whether this is a default behavior for the TreeView or a bug of some sort, but until I find out, I’m leaving it as it is. I did use a TreeViewItem’s MouseOver state which wasn’t in the original template, so it may be that this state is not (properly) supported. Anyway, I’ll definitely get back to this, but first we have some adding to do.
Next in the series: adding an item
The source code for this sample is available: