In Focus

Overview Of Composite Collection In WPF

Recently in our project, which is based on WPF framework, we wanted to use ItemsControl to list out different types of objects. I couldn’t use general List, ObservableCollection or any other type of collection for that matter to set ItemSource of ItemsControl, since they restrict only one type of object. Thus, I searched on the internet and found out about CompositeCollection. In this article I am going to explain how to use CompositeCollection to list out different types of objects in WPF.

Recently in our WPF project, we wanted to use ItemsControl to list out different types of objects. I couldn’t use the general List, ObservableCollection, or any other type of collection, for that matter, to set ItemSource of ItemsControl since they restrict only one type of object. Thus, I searched on the internet and found out about CompositeCollection. In this article, I am going to explain how to use CompositeCollection to list out different types of objects in WPF.

Requirements

To understand how to use CompositeCollection to list out a variety of objects in a single list, we need to go through what we are trying to achieve here.

Composite Collection In WPF 

The above WPF application is a conversation view for a test chat application. In this conversation view, we have ItemsControl to list out the messages. The only tricky part here is that we have different types of objects, i.e., InboundMessage and OutboundMessage. InboundMessage objects will appear on the left side and the OutboundMessage objects will appear on the right-hand side. Thus, we will use CompositeCollection along with DataTemplate of ItemsControls to achieve these results.

I am going to explain steps in terms of modules in this project.

Model

We are going to create two objects - InboundMessage and OutboundMessage. Each of these will have corresponding properties which we’ll bind to the main UI and in addition to that, it will have one static method that returns ObservableCollection of corresponding objects.

  1. public class InboundMessage  
  2. {  
  3.     public int MessageId { set; get; }  
  4.     public string TextMessage { set; get; }  
  5.     public DateTime ReceivedTime { set; get; }  
  6.   
  7.     public static ObservableCollection<InboundMessage> GetInboundMessages()  
  8.     {  
  9.         //return ObservableCollection of InboundMessage  
  10.     }  
  11. }  

Similarly, we will have OutboundMessage object.

Controls

We will create two UserControls to represent these model objects - InboundMessage and OutboundMessage -- and we'll bind the properties of these objects to corresponding controls.

  1. <Grid.RowDefinitions>  
  2.   <RowDefinition Height="3*"/>  
  3.   <RowDefinition Height="1*"/>  
  4.        </Grid.RowDefinitions>  
  5. <Border Grid.Row="0" Background="White" CornerRadius="10" Padding="10"          Margin="5,5,5,0" HorizontalAlignment="Left">  
  6.            <Grid>  
  7.                <Grid.RowDefinitions>  
  8.                    <RowDefinition Height="3*"/>  
  9.                    <RowDefinition Height="1*"/>  
  10.                </Grid.RowDefinitions>  
  11.   
  12.                <TextBlock Name="tbTextMessage"   
  13.                           TextWrapping="Wrap"  
  14.                           FontSize="{Binding InboundMessageBubbleFontSize, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}"  
  15.                           Text="{Binding TextMessage, RelativeSource={RelativeSource   Mode=FindAncestor, AncestorType=UserControl}}"/>  
  16.                <TextBlock Name="lblTimeStamp"  
  17.                       Grid.Row="2"    
  18.                       Padding="0"   
  19.                       HorizontalAlignment="Right"  
  20.                       Text="{Binding TimeStamp, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}">  
  21.                </TextBlock>  
  22.            </Grid>  
  23.        </Border>  
  24. <Path Grid.Row="1" Stroke="Black" Fill="White" StrokeThickness="0" Data="M 12,0 L 18,10 L 25,0"/>  

Now, for the main control which is going to be a list to display these objects, even though there are many list controls in WPF, we are going with simple ItemsControl because we don’t need selection events for our view. We will also use scroll viewer to provide scrolling functionality.

We’ll use two DataTemplates to represent Inbound and Outbound message controls. Now the problem is we can only set one data template in datatemplate property of ItemsControl. To overcome this, we will create multiple DataTemplate in the resource property of ItemsControl.

Since our collection is going to have multiple objects and ItemsControl is going to have multiple DataTemplates we need selector which will apply data template to object. For this, we set DataType property of DataTemplate, which sets that template to that object only.

E.g.

<DataTemplate DataType="{x:Type localmodel:InboundMessage}">

The above DataTemplate will be applied to only InboundMessages.

  1. <ScrollViewer VerticalScrollBarVisibility="Auto" Background="CadetBlue">  
  2.             <ItemsControl Name ="conversationList">  
  3.                 <ItemsControl.Resources>  
  4.                     <DataTemplate DataType="{x:Type localmodel:InboundMessage}">  
  5.                         <localcontrols:InboundMessageBubble  
  6.                                Margin="0,0,100,0"  
  7.                                HorizontalAlignment="Left"  
  8.                                InboundMessageBubbleFontSize="24"  
  9.                                TextMessage="{Binding TextMessage}"  
  10.                                TimeStamp="{Binding ReceivedTime,            Converter={StaticResource objectToString}}"/>  
  11.                     </DataTemplate>  
  12.                     <DataTemplate DataType="{x:Type localmodel:OutboundMessage}">  
  13.                         <localcontrols:OutboundMessageBubble  
  14.                                Margin="100,0,0,0"  
  15.                                HorizontalAlignment="Right"  
  16.                                OutboundMessageBubbleFontSize="24"  
  17.                                TextMessage="{Binding TextMessage}"  
  18.                                TimeStamp="{Binding SentTime, Converter={StaticResource objectToString}}"/>  
  19.                     </DataTemplate>  
  20.                 </ItemsControl.Resources>  
  21.             </ItemsControl>  
  22.         </ScrollViewer>  

The above code will apply different DataTemplates to Inbound and Outbound objects.

Helper

We can convert most of the objects to a string using ToString() method in code behind. But to do the same thing in XAML, we will have Helper class in our project which is a Converter class in WPF that converts any Object to String.

  1. public class StringFormatConverter : BaseConverter, IValueConverter  
  2. {  
  3.     public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)  
  4.     {  
  5.         string format = parameter as string;  
  6.         if (!string.IsNullOrEmpty(format))  
  7.         {  
  8.             return string.Format(culture, format, value);  
  9.         }  
  10.         else  
  11.         {  
  12.             return value.ToString();  
  13.         }  
  14.     }  
  15.   
  16.     public object ConvertBack(object value, Type targetType, object parameter,System.Globalization.CultureInfo culture)  
  17.     {  
  18.         return null;  
  19.     }  
  20. }  

Final Step

The final step is to take both objects using their corresponding static methods.

  1. ObservableCollection<InboundMessage> inboundMessages = new ObservableCollection<InboundMessage>();  
  2. ObservableCollection<OutboundMessage> outboundMessages = new ObservableCollection<OutboundMessage>();  
  3. inboundMessages = InboundMessage.GetInboundMessages();  
  4. outboundMessages = OutboundMessage.GetOutboundMessages();  

Assign these ObservableCollections to Collection property of CollectionContainer objects. Then, add these Collection Containers to CompositeCollection using its Add method as follows.

  1. compositeCollection.Add(new CollectionContainer() { Collection = inboundMessages });  
  2. compositeCollection.Add(new CollectionContainer() { Collection = outboundMessages });  

Lastly, set ItemSource property of ItemsControl  with this composite collection.

  1. conversationList.ItemsSource = compositeCollection;