Mega Code Archive

 
Categories / C# / WPF
 

Data binding using collections composed of mixed types of data

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"   xmlns:c="clr-namespace:WpfApplication1"   x:Class="WpfApplication1.Window1"   Title="CompositeCollections"   SizeToContent="WidthAndHeight">   <Window.Resources>     <c:Employees x:Key="EmployeesData"/>     <XmlDataProvider x:Key="NewStudentesData" XPath="NewStudentes/Student">       <x:XData>       <NewStudentes xmlns="">         <Student Name="Jason" />         <Student Name="Hercules" />         <Student Name="Bellerophon" />         <Student Name="Theseus" />         <Student Name="Odysseus" />         <Student Name="Perseus" />       </NewStudentes>       </x:XData>     </XmlDataProvider>     <DataTemplate DataType="{x:Type c:Employee}">       <TextBlock Text="{Binding Path=Name}" Foreground="Gold"/>     </DataTemplate>     <DataTemplate DataType="Student">       <TextBlock Text="{Binding XPath=@Name}" Foreground="Cyan"/>     </DataTemplate>   </Window.Resources>      <StackPanel>     <ListBox Name="myListBox" Height="300" Width="200">       <ListBox.ItemsSource>         <CompositeCollection>           <CollectionContainer Collection="{Binding Source={StaticResource EmployeesData}}" />           <CollectionContainer Collection="{Binding Source={StaticResource NewStudentesData}}" />           <ListBoxItem Foreground="Red">Other Listbox Item 1</ListBoxItem>         </CompositeCollection>       </ListBox.ItemsSource>     </ListBox>   </StackPanel> </Window> //File:Window.xaml.cs using System; using System.ComponentModel; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Data; using System.Collections.ObjectModel; namespace WpfApplication1 {   public partial class Window1 : Window   {     public Window1()     {       InitializeComponent();     }   }   public class Employee   {         private string _name;     public string Name     {             get             {                 return _name;             }             set             {                 _name = value;             }     }                  public Employee(string name)         {             Name = name;         }   }   public class Employees : ObservableCollection<Employee>   {     public Employees()     {       Add(new Employee("A"));       Add(new Employee("B"));       Add(new Employee("C"));     }   } }