如果您有單一級別Parent
和Child
您可以做這樣的事情。
一個簡單的代碼隱藏了一些樣本數據
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; }
}
}
XAML中會是這樣的。
<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>
這樣的結果是這樣的。我省略了所有的造型爲簡單起見,我相信你可以讓它更加性感;)
現在你可以只處理Child
後面的代碼IsSelected
真正
如果你有一個以上一個水平... ..即你孩子有孩子你將不得不使用HierarchicalDataTemplate
原諒我的XAML中,我是從我的頭 – Christian
頂部打字這是一個簡單的父/子關係?孩子們可以生孩子嗎? – cadrell0
在這種情況下,孩子們沒有孩子 – Christian