将子项与主项绑定到同一控件WPF

时间:2013-08-08 09:08:32

标签: wpf xaml data-binding wpfdatagrid

如何将对象List绑定到具有主要项和子项的控件。如果类结构是这样的

public class BookChapter
{
 public string Name { get; set; }
 public List<BookPage> Pages {get; set; }
 public List<String> Questions { get; set; }

}
public class BookPage
{
    public string Id { get; set; }
    public string Name { get; set; }
    public List<String> Excercises { get; set; }
}

如何在WPF控件上绑定它,其中ChapterName和Pages与单个控件中的每个章节相关联。

1 个答案:

答案 0 :(得分:2)

在WPF中有几种方法可以实现这一点,一种方法是使用DataTemplates来描述您希望如何显示对象。使用ItemsControl或派生控件来显示您的馆藏:

我经常把我的风格分成不同的类型,以使它们更容易阅读,例如:

<Window x:Class="WpfApplication2.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication2"
    Title="MainWindow" Height="350" Width="525"
    DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Window.Resources>

    <!-- Book Chapters -->
    <DataTemplate DataType="{x:Type local:BookChapter}">
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="{Binding Path=Name}" />
            <ItemsControl ItemsSource="{Binding Path=Pages}" />
        </StackPanel>
    </DataTemplate>

    <!-- Book Pages -->
    <DataTemplate DataType="{x:Type local:BookPage}">
        <StackPanel Orientation="Horizontal" >
            <TextBlock Text="{Binding Path=Id}" Margin="5 0"/>
            <TextBlock Text="{Binding Path=Name}" Margin="5 0"/>
            <ItemsControl ItemsSource="{Binding Path=Exercises}" />
        </StackPanel>
    </DataTemplate>

</Window.Resources>
<Grid>
    <ListBox ItemsSource="{Binding Path=Chapters}" />
</Grid>

这将产生类似于此的内容(基于我填充对象的内容):enter image description here

在不模板化对象的情况下,WPF只会将集合显示为ApplicationName.ClassName - ToString的结果,模板可让您定义如何显示类的显示方式

您可以将这些模板保存在单独的资源文件中,并在需要时在整个应用程序中重复使用它们。重要的是要注意,因为我正在模仿实际的Type,所以只要您的对象在此特定Window中显示,就会使用此模板,除非您另行指定。

您可以通过命名它们来添加对这些模板何时/何时使用的更大控制,并且只将它们应用于特定组件(http://msdn.microsoft.com/en-us/library/ms742521.aspx)。