首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >WPF绑定子控件DataContext到HierarchicalDataTemplate ItemsSource项

WPF绑定子控件DataContext到HierarchicalDataTemplate ItemsSource项
EN

Stack Overflow用户
提问于 2022-01-17 20:31:09
回答 1查看 58关注 0票数 1

我有一个条形码集合,其中包含一个职位集合。如何将自定义控件的DataContext设置为集合中的位置项?

代码语言:javascript
运行
复制
    <TreeView ItemsSource="{Binding SelectedPlate.Barcodes}">
        <TreeView.ItemTemplate>
            <HierarchicalDataTemplate ItemsSource="{Binding Positions}"
                                  DataType="{x:Type ControlViewModels:BarcodeViewModel}">

                <TextBox Text="{Binding Code}"/>

                <HierarchicalDataTemplate.ItemTemplate>
                    <DataTemplate>

                        <!--The Custom Control that needs to bind to the Position item-->
                        <ControlViews:PositionControl DataContext="{Binding}"/>
                        
                    </DataTemplate>
                </HierarchicalDataTemplate.ItemTemplate>
            </HierarchicalDataTemplate>
        </TreeView.ItemTemplate>

    </TreeView>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-01-17 21:10:20

ItemTemplate中的根元素继承了DataContext,因此可以删除DataContext="{Binding}"

代码语言:javascript
运行
复制
<TreeView ItemsSource="{Binding SelectedPlate.Barcodes}">
    <TreeView.ItemTemplate>
        <HierarchicalDataTemplate ItemsSource="{Binding Positions}"
                                  DataType="{x:Type ControlViewModels:BarcodeViewModel}">
            <TextBox Text="{Binding Code}"/>
            <HierarchicalDataTemplate.ItemTemplate>
                <DataTemplate>
                    <ControlViews:PositionControl />
                </DataTemplate>
            </HierarchicalDataTemplate.ItemTemplate>
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
</TreeView>

PositionControl中,如果没有显式设置控件的DataContext,则可以直接绑定到Position对象的公共属性。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70747178

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档