【问题标题】:WPF, Data Binding, Lookup hierarchyWPF、数据绑定、查找层次结构
【发布时间】:2012-12-03 12:44:03
【问题描述】:

我是 WPF 新手,正在尝试使用 DataBinding 遵循 MVVM 范例开发一个小型应用程序。

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

这里有一个问题 - 如何创建与父标签的查找绑定?在按钮单击命令上,我想传递文档路径,该路径在第一个 DataTemplate 中可用。

有没有办法解决这个问题? 你会建议如何绕过它?

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

这里是代码https://gist.github.com/b5760982ba81e8ee4036,第 14 行

【问题讨论】:

    标签: c# .net wpf binding


    【解决方案1】:

    你应该使用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>
    

    【讨论】:

    • 就像一个魅力。非常感谢。我不知道 ContentPresenter :) 再次感谢
    • 完成 :) 请快速跟进... gist.github.com/0a556bc1553fe3f24d3d 对于旧绑定,我使用了静态绑定,我不喜欢它。但是,我也不是很喜欢新的。请问有什么推荐的吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-29
    相关资源
    最近更新 更多