Changing Itemtemplate to show details in when selected
May 11, 2008 by lee
There are places in which we want to show the details of an Item(ex. listboxitem) when it selected. As it is not easy to get the actual item(listbox item), we have to add some code to get a handle to the control when the controls are getting loaded
lets say we have this XAML
<UserControl x:Class=”SilverlightApplication10.Page”
xmlns=”http://schemas.microsoft.com/client/2007“
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml“
Width=”400″ Height=”300″>
<UserControl.Resources>
<Style x:Key=”st1″ TargetType=”TextBlock”>
<Setter Property=”Foreground” Value=”White”></Setter>
<Setter Property=”FontFamily” Value=”Tahoma”></Setter>
<Setter Property=”FontSize” Value=”12″></Setter>
</Style>
<DataTemplate x:Key=”dtContent”>
<ContentPresenter Width=”200″ x:Name=”cp” Loaded=”cp_Loaded” ></ContentPresenter>
</DataTemplate>
<DataTemplate x:Key=”dt”>
<StackPanel Background=”#333333″ Width=”200″ HorizontalAlignment=”Stretch”>
<TextBlock Style=”{StaticResource st1}” Margin=”5,0,0,0″ Text=”{Binding FirstName}”></TextBlock>
<StackPanel Margin=”5,0,0,0″ Loaded=”StackPanel_Loaded_1″ Visibility=”Collapsed”>
<TextBlock FontWeight=”Bold” Text=”Details:” Style=”{StaticResource st1}”></TextBlock>
<TextBlock Style=”{StaticResource st1}” Text=”{Binding Details}”></TextBlock>
</StackPanel>
</StackPanel>
</DataTemplate>
</UserControl.Resources>
<Canvas>
<ListBox Canvas.Left=”50″ Canvas.Top=”50″ x:Name=”list1″ ItemTemplate=”{StaticResource dt}”>
</ListBox>
<ListBox Canvas.Left=”300″ Canvas.Top=”50″ x:Name=”list2″ ItemTemplate=”{StaticResource dtContent}” >
</ListBox>
</Canvas>
</UserControl>
In the first listbox initially we display just the firstname and when the item is selected we want to show additional details, we wrap the content that we want to be displayed only when it is selected in a panel and handle the loaded event to save a reference to it, so we can refer to it and toggle the visibility from ‘Collapsed’ to Visible’
List<StackPanel> _items = new List<StackPanel>();
private void StackPanel_Loaded_1(object sender, RoutedEventArgs e)
{
_items.Add(sender as StackPanel);
}
void list1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (list1PreviousIndex > -1)
_items[list1PreviousIndex].Visibility = Visibility.Collapsed;
_items[list1.SelectedIndex].Visibility = Visibility.Visible;
list1PreviousIndex = list1.SelectedIndex;
}

The listbox on the left toggles the panels visibility when selected. the listbox on the right does the same thing, the only difference is the itemtemplate is actually a UserControl. we want to change the usercontrol when the listboxitem is displayed, for this we use ContentPresenter in the datatemplate, get a reference to it and change its contents