WPF,数据绑定,查找层次结构

时间:2012-12-03 12:44:04

标签: c# .net wpf binding

我是WPF的新手,并试图在MVVM范例之后使用DataBinding开发一个小应用程序。

我正在尝试为Document的ObservableCollection(我的类型)提供绑定功能。第一个标签将显示一个文档路径(通过属性属性可用),而下一个子项 - 文档页面 - 将显示适当的信息:页面索引和页面内容(图像)。

这是一个问题 - 如何创建与父Label的查找绑定? On Button Click命令我想传递文档路径,该路径在第一个DataTemplate中可用。

有没有办法解决这个问题? 你会怎么推荐绕过它?

另外,有没有更好的方法来解决“嵌套”结构(集合中的集合)?

以下是代码https://gist.github.com/b5760982ba81e8ee4036,第14行

1 个答案:

答案 0 :(得分:0)

你应该使用RelativeSource:

<ItemsControl ItemsSource="{Binding Documents}">
<ItemsControl.ItemTemplate>
    <DataTemplate>
        <StackPanel>
            <Label Content="{Binding Path=Attribute.Path}"/>
                <ItemsControl ItemsSource="{Binding Pages}">
                    <ItemsControl.ItemTemplate>
                        <DataTemplate>
                            <StackPanel>




<Label Content="{Binding Index}"/>
                                <Button Content="{Binding Content}"
                                        Command="{x:Static viewModel:DocViewModel.Tests }" 
                                        CommandParameter="{Binding Path=DataContext.Attribute.Path,RelativeSource={RelativeSource AncestorType=ContentPresenter, Mode=FindAncestor,AncestorLevel=2"/> 
                            </StackPanel>
                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                </ItemsControl>
            </StackPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>