2011-11-18 79 views
2

我有一個容器類型控件,其中包含多個項目。容器控件的DataTemplate已定義,其中還包含ItemsControl,該項目的DataTemplate。但是,這些項目需要綁定到容器控件的某些內容。一個簡單的例子如下:如何從ItemsControl.ItemTemplate中綁定到父DataTemplate

<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> 

如何在項目級別綁定一些東西到容器級別?

回答

1

也許使用TemplateBinding?

喜歡的東西:

{TemplateBinding YourPropertyInTheDataTemplateContext} 
+1

TemplateBinding僅適用於CONTROLTEMPLATES,據我所知。 –

6

您可以使用RelativeSource結合

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

您用於綁定路徑是什麼取決於其中收集所在。如果它位於DependencyPropertyMyContainerControl上,那麼上面的綁定工作正常。如果它位於的MyContainerControlDataContext,那麼你就需要將結合路徑設置爲DataContext.SomeCollection

+0

集合是ContainerType DataTemplate的DataContext中的一個屬性,所以我嘗試了'ItemsSource = {{Binding RelativeSource = {RelativeSource FindAncestor,AncestorType = {x:Type local:ContainerType}},Path = DataContext.AvailableJobs}'。上面的表格,但都沒有工作... –

+0

@BrianTriplett從綁定 – Rachel

+0

中刪除'FindAncestor',但仍然沒有在ComboBox中顯示集合當你說'MyContainerControl'你指的是我所謂的ContainerType '在我的示例代碼中,或者是指包含'ContainerType'的DataTemplate的控件(在本例中爲ContentControl')? –

1

我一直的ElementName忠實粉絲。基本上,你要確保你的名字一樣外水位控制:x:Name="MainWin",然後你可以做這樣的事情:

<DataTemplate> 
     <StackPanel Orientation="Horizontal"> 
       <ComboBox ItemsSource="{Binding ElementName=MainWin, Path=DataContext.SomeCollection}"/> 
+0

這不起作用。 DataTemplate在可視化樹中沒有得到明確的名稱,因此可以通過'ElementName'來引用它 –

+0

我曾經這麼想過,但我向你保證,我已經在WPF項目中工作了。剛剛測試過它。你在使用Silverlight嗎?下面是從我實際工作的代碼剪切/過去: –

+0

' <按鈕命令=「{結合DeleteSkillSetCommand ,ElementName = MainWin}「CommandParameter =」{Binding''} Style =「{StaticResource SimpleButtonStyle}」Margin =「5」x:Name =「DeleteSkillSet」VerticalAlignment =「Center」Horizo​​ntalAlignment =「Left」>

相關問題