If you have a single level of Parent
and Child
you can do something like this.
A simple codebehind with some sample data
namespace SilverlightApplication2
{
public partial class MainPage : UserControl
{
public ObservableCollection<Parent> ParentList { get; set; }
public MainPage()
{
Populate();
InitializeComponent();
}
private void Save_Click(object sender, RoutedEventArgs e)
{
foreach (var child in ParentList
.SelectMany(p => p.Children)
.Where(c => c.IsSelected))
{
//Save the child
Debug.WriteLine(string.Format("Child {0} saved", child.Name));
}
}
private void Populate()
{
ParentList = new ObservableCollection<Parent>();
ParentList.Add(new Parent
{
Name = "John",
Children = new List<Child> { new Child { Name = "Paul" }, new Child { Name = "Pat" } }
});
ParentList.Add(new Parent
{
Name = "Mike",
Children = new List<Child> { new Child { Name = "Bob" }, new Child { Name = "Alice" } }
});
ParentList.Add(new Parent
{
Name = "Smith",
Children = new List<Child> { new Child { Name = "Ryan" }, new Child { Name = "Sue" }, new Child { Name = "Liz" } }
});
}
}
public class Parent
{
public string Name { get; set; }
public List<Child> Children { get; set; }
}
public class Child
{
public string Name { get; set; }
public bool IsSelected { get; set; }
}
}
Your xaml would be something like this.
<UserControl x:Class="SilverlightApplication2.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:my="clr-namespace:SilverlightApplication2"
x:Name="MainUserControl"
Width="400"
Height="300"
mc:Ignorable="d">
<UserControl.Resources>
<DataTemplate x:Key="ChildTemplate">
<StackPanel Orientation="Horizontal">
<CheckBox IsChecked="{Binding IsSelected}"/>
<TextBlock Text="{Binding Name}" />
</StackPanel>
</DataTemplate>
<DataTemplate x:Key="ParentTemplate">
<StackPanel>
<TextBlock Text="{Binding Name}" />
<ListBox ItemsSource="{Binding Path=Children}" ItemTemplate="{StaticResource ChildTemplate}"/>
</StackPanel>
</DataTemplate>
</UserControl.Resources>
<StackPanel x:Name="LayoutRoot" Background="White">
<ListBox ItemsSource="{Binding ElementName=MainUserControl, Path=ParentList}" ItemTemplate="{StaticResource ParentTemplate}"/>
</StackPanel>
</UserControl>
This results in a view like this. I have omitted all styling for simplicity, I am sure you can make it more sexy ;)
Now you can in the code behind only process Child
with IsSelected
true
If you have more than one level... ie..Your Children have children you will have to use the HierarchicalDataTemplate