2013-06-19 75 views
6

好了,所以我在這裏有一個時髦的一個......我需要能夠從一個孩子的ItemsControl數據模板內綁定到父母的ItemsControl的屬性:WPF從孩子的ItemsControl數據模板內部綁定於母公司的ItemsControl

<ItemsControl ItemsSource="{Binding Path=MyParentCollection, UpdateSourceTrigger=PropertyChanged}"> 
    <ItemsControl.ItemTemplate> 
     <DataTemplate> 

       <ItemsControl ItemsSource="{Binding Path=MySubCollection}"> 
        <ItemsControl.ItemTemplate> 
         <DataTemplate> 
          <TextBlock Text="{Binding Path=MyParentCollection.Value, UpdateSourceTrigger=PropertyChanged}"/> 
         </DataTemplate> 
        </ItemsControl.ItemTemplate> 
       </ItemsControl> 

     </DataTemplate> 
    </ItemsControl.ItemTemplate> 
</ItemsControl> 

讓我們假設MyParentCollection(外集合)是以下類型:

public class MyObject 
{ 
    public String Value { get; set; } 
    public List<MyChildObject> MySubCollection { get; set; 
} 

而且讓我們假設MyChildObject從上面的類是以下類型:

public class MyChildObject 
{ 
    public String Name { get; set; } 
} 

如何從內部數據模板內部綁定到MyParentCollection.Value?我無法按類型使用FindAncestor,因爲它們都使用相同的類型。我想也許我可以在外部集合上放置一個名稱並在內部綁定中使用ElementName標籤,但仍然無法解析該屬性。

有什麼想法?我卡在這一個...

+0

您不能使用FindAncestor模式,並指定Type和Ancestor級別? –

+0

嗯,甚至沒有想到祖先的水平...我會看看那 –

+0

我似乎無法得到那個工作,哦以及 –

回答

12

保存在孩子的標籤的父項的ItemsControl可以工作

<DataTemplate> 

      <ItemsControl ItemsSource="{Binding Path=MySubCollection}" Tag="{Binding .}"> 
       <ItemsControl.ItemTemplate> 
        <DataTemplate> 
         <TextBlock Text="{Binding Path=Tag.Value, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"/> 
        </DataTemplate> 
       </ItemsControl.ItemTemplate> 
      </ItemsControl> 

    </DataTemplate> 

它不是測試,但給你一個正確的方向提示:)

+0

這似乎很有前途...我會後來和這個混亂和讓你知道它是如何工作的 –

+0

經過測試,這確實工作得很好......對未經測試但工作代碼的讚譽,沒有什麼必須從你的代碼中改變 –

+0

當天的黑客,但仍然保存了一天。非常感謝你!我希望標記綁定只是簡單地引用綁定上下文,而不會重複上下文中的內容。 – 2014-01-23 18:34:14

相關問題