In the previous post, we enabled editing for our TreeView. The last operation we need to implement is adding a new item to the hierarchy. With our tree item editor in place, there’s not so much left to do…
The only change we need to make with the View is add an Add button, right next to the Edit button. We’ll wire it to the Add command, which already exists.
The next stop is the ViewModel. We need to change the existing OnAddTopicExecuted handler to add a new child to the HelpTopic, passed into the method through CommandParameter:
private void OnAddTopicExecuted(object sender, ExecutedEventArgs e)
{
HelpTopic topic = new HelpTopic();
HelpTopic parent = e.Parameter as HelpTopic;
if (parent == null)
{
HelpTopics.Add(topic);
}
else
{
parent.SubTopics.Add(topic);
}
topic.BeginEdit();
}
Note: when CommandParameter is not set to a valid HelpTopic (when it’s null), we’re adding a child to the root.
There is something wrong with the code above. I’m assuming that the SubTopics collection was already initialized when I created a new HelpTopic class instance. I this case, I assumed wrong and the above code would throw a nasty error.
I need to assure that SubTopics property is never null as this puts the HelpTopic in an invalid state. I’ll do that by inserting the collection initialization code in its constructor:
public HelpTopic()
{
SubTopics = new ObservableCollection<HelpTopic>();
}
Better. But we’re not done yet. There is no way for user to cancel the newly added item. Sure, she can press the Cancel button when editing, but the node will not be removed from the tree.
This is the time to provide the HelpTopic class with an unique identificator field. When working with the database, the type of this field would align with whatever your database table primary key type is. For simplicity, I’ll use Guids here, just because their generation results in more unique results than a number randomization would.
The logic behind is this: when a new HelpTopic is being added, its Id is set to null. If the item is confirmed, the new Id is set, otherwise the item is removed from the hierarchy. Here’s how modified OnEndEditTopic and OnCancelEditTopic now look like:
private void OnEndEditTopic(object sender, ExecutedEventArgs e)
{
HelpTopic topic = e.Parameter as HelpTopic;
if (!topic.Id.HasValue)
{
topic.Id = Guid.NewGuid();
}
topic.EndEdit();
}
private void OnCancelEditTopic(object sender, ExecutedEventArgs e)
{
HelpTopic topic = e.Parameter as HelpTopic;
if (!topic.Id.HasValue)
{
topic.RemoveFromStructure(HelpTopics, item => { return item.SubTopics; });
}
topic.CancelEdit();
}
Wait! Before we end this, let me just put another button in a TreeView to enable user to add a new HelpTopic to the root of the tree. This is the modified template with a new button in place (added lines in bold italic):
<ControlTemplate TargetType="slt:TreeView">
<Grid x:Name="Root" >
<Grid.Resources>
<SolidColorBrush x:Key="BorderBrush" Color="#FF000000" />
</Grid.Resources>
<Border x:Name="Border" BorderBrush="{StaticResource BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="2">
<Border Padding="{TemplateBinding Padding}" Background="{TemplateBinding Background}" Margin="1">
<ScrollViewer x:Name="ScrollViewer" HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Auto" Background="{x:Null}" BorderBrush="Transparent"
BorderThickness="0" IsTabStop="False" TabNavigation="Once">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Button HorizontalAlignment="Left"
ToolTipService.ToolTip="Add Topic"
input:CommandService.Command="AddTopic">
<Image Source="/EditableTreeView;component/Resources/add.png" Stretch="None" />
</Button>
<ItemsPresenter x:Name="TreeItems" Grid.Row="1" Margin="5" />
</Grid>
</ScrollViewer>
</Border>
</Border>
</Grid>
</ControlTemplate>
OK, we’ve got our TreeView to allow basic inline editing now, but not in very realistic scenario and it lacks usability. I’m going to end this series with this post and spin off to more general topics posts, covering more MVVM, LOB scenarios and Silverlight in general. A taste of things to come: improving, extending and expanding on the current state of this sample, going over the wire, testing and user experience.
The source code for this sample is available:
d0071cd2-ceeb-411e-988b-e50f50fce241|6|5.0|27604f05-86ad-47ef-9e05-950bb762570c