2013-07-29 162 views
1

這讓我瘋狂。 也許我設計我的數據是錯誤的,但我試圖綁定到來自父項ItemsControl的活動項目。如何綁定到NESTED ItemsControl的活動ItemsControl項目

每個區域都有一個顏色,以便在屏幕上輕鬆識別。我沒有給每個座位賦予顏色屬性,而是在「區域」模型中植入顏色。所有兒童座椅都需要使用該顏色來繪畫自己。

無論我嘗試什麼,我都無法到達父項目控件,因此我可以獲取該特定區域的活動顏色屬性。

模型(簡體)

public class BuildingLayout 
{ 
    public ObservableCollection<Area> Areas { get; set; } 
} 

public class Area 
{ 
    public Color Color { get; set; } // The color I want to bind to 
    ... 
    public ObservableCollection<Table> Tables { get; set; } 
} 

public class Table 
{ 
    public int Seat { get; set; } // The seat needs to get the area color 
} 

XAML

<ItemsControl ItemsSource="{Binding Path=Areas}"> 
    ... 
    <ItemsControl.ItemTemplate> 
     <!-- Nested Listbox --> 
     <ItemsControl ItemsSource="{Binding Path=Tables}"> 
       ... 
       <ItemsControl.ItemTemplate> 
        <DataTemplate> 
         <!-- Now I want to get to the color property of 
          the parent (Area) --> 
         <Rectangle Fill="{Binding ..., Path=Color}" /> 
        </DataTemplate> 
       </ItemsControl.ItemTemplate> 
     </ItemsControl> 
    </ItemsControl.ItemTemplate> 
</ItemsControl> 

回答

6
<Rectangle Fill="{Binding DataContext.Color, RelativeSource={RelativeSource AncestorType=ItemsControl}"/> 

因爲嵌套ItemsControlItemTemplate對於父一個的內部,因此它具有Area實例因爲它是DataContext。

+0

這很有道理。 Awesomecakes! –

相關問題