wpf - 如何从 ItemsControl.ItemTemplate 绑定(bind)到父 DataTemplate

标签 wpf data-binding datatemplate

我有一个包含许多项目的容器类型控件。容器控件定义了一个 DataTemplate,它还包含一个带有 DataTemplateItemsControl。然而,这些项目需要绑定(bind)到容器控件中的某些内容。下面给出了一个简化的例子:

<DataTemplate DataType="{x:Type ContainerType}">

    <!-- Display of the container stuff-->

    <ItemsControl ItemsSource="{Binding Items, Mode=OneWay}">

        <ItemsControl.ItemTemplate>
              <DataTemplate DataType="{x:Type Item}">

                  <!-- Display of the item stuff -->
                  <ComboBox Text="Choose a container-level option..."
                            ItemsSource="{WHAT GOES HERE?}"/>

                </DataTemplate>
         </ItemsControl.ItemTemplate>

      </ItemsControl>
</DataTemplate>

如何将项目级别的内容绑定(bind)回容器级别?

最佳答案

您可以使用RelativeSource 绑定(bind)

<ComboBox ItemsSource="{Binding SomeCollection, 
              RelativeSource={RelativeSource 
                  AncestorType={x:Type local:MyContainerControl}}}"/>

您使用什么作为绑定(bind)路径取决于集合所在的位置。如果它作为 MyContainerControl 上的 DependencyProperty 定位,则上述绑定(bind)工作正常。如果它位于 MyContainerControlDataContext 中,则需要将绑定(bind)路径设置为 DataContext.SomeCollection

关于wpf - 如何从 ItemsControl.ItemTemplate 绑定(bind)到父 DataTemplate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8184972/

相关文章:

javascript - 使用 AngularJS 绑定(bind)图像标签

wpf - 通过两个级别绑定(bind)到 TemplatedParent

wpf - 获取数据模板中的数据项

c# - wpf:usercontrol 与 customcontrol 性能问题

wpf - 我可以根据某些条件对相同的数据类型使用不同的数据模板吗?

WPF ListBox WrapPanel 剪辑长组

c# - 自定义字符串格式 0,0 带斜杠或反斜杠

c# - WPF - 具有 MultiBinding 和不同 DataContexts 的自定义工具提示

c# - 在 datagridview 中选择一个单元格并开始编辑

wpf - 刷新 OxyPlot 图表