wpf - 将子项与主项一起绑定(bind)到同一控件 WPF

标签 wpf xaml data-binding wpfdatagrid

我们如何将一个对象列表绑定(bind)到一个控件及其主要项目和子项目。如果类结构是这样的

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; }
}

我如何将它绑定(bind)到一个 WPF 控件上,其中 ChapterName 和 Pages 与单个控件中的每个章节相关联。

最佳答案

在 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 的结果,模板使您能够定义您希望如何显示您的类(class)。

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

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

关于wpf - 将子项与主项一起绑定(bind)到同一控件 WPF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18122057/

相关文章:

wpf - 项目控制 : How to print WrapPanel on multiple Pages?

c# - 使用 ComboBox 更改 CollectionViewSource 过滤器

wpf - WPF 中的双向绑定(bind)

c# - 资源字典中的 Wpf 数据绑定(bind)

安卓数据绑定(bind) : "Method references using ' .' is deprecated"

wpf - Visual Studio 2013 保存文件速度极慢

c# - 什么时候真正对 WPF 控件使用 Freeze()?

c# - ObservableCollection 逐元素变换/投影包装器

以 MS Access 数据库作为数据源的 WPF 应用程序

c# - 将 TextBox 中的值传递给 ValidationRule