项目控制.ItemTemplate绑定到与ItemsControl不同的集合

本文关键字:集合 ItemsControl 控制 ItemTemplate 绑定 项目 | 更新日期: 2023-09-27 17:59:26

我有一个带有ItemsControl的绑定树视图,它在运行时动态创建树视图项。然而,为了做到这一点,我将ItemsControl ItemsSource绑定到了与树视图绑定到的集合不同的集合。这很有效,但问题是绑定ItemsContext中的文本框,应该显示的实际上是SubOrganLocations的成员,但我似乎无法使绑定正常工作。无论我做什么,WPF都希望绑定到ItemsControl ItemsSource的属性ProjectOrganLocation.LesionTypes,而不是SubOrganLocations。下面是树的XAML 的一个片段

<TreeView ItemsSource="{Binding GlobalOrganTree}">
<TreeView.ItemTemplate>
    <HierarchicalDataTemplate ItemsSource="{Binding SubOrganLocations}">
        <StackPanel Orientation="Horizontal">     
        <ItemsControl x:Name="ItemsControlGrid" ItemsSource="{Binding Path=ProjectOrganLocation.LesionTypes, Source={StaticResource Locator}}" >
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                     <StackPanel Orientation="Horizontal" />
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding SubOrganLocations, Path=OrganLocation.Labels}"
                         Width="75" 
                         TextAlignment="Center"/>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
        </StackPanel>
   </HierarchicalDataTemplate>
</TreeView.ItemTemplate>

如何将文本框绑定到SubOrganLocations属性而不是ProjectOrganLocation.LesionTypes属性?

项目控制.ItemTemplate绑定到与ItemsControl不同的集合

RelativeSource在需要绑定到树中较高的DataContext时很常见:

<TextBox Text="{Binding Path=DataContext.Labels, RelativeSource={RelativeSource AncestorType={x:Type TreeViewItem}}}" />

这绑定到TreeViewItems的DataContext(一个器官)并从中获取标签。