2010-06-11 86 views
0

我真的不知道如何標題這個問題,但我需要一些幫助與綁定到列表框。WPF - 在已綁定的ListBox中綁定一個變量?

我有一個對象,它包含(除其他信息外)需要在一個ListBox中綁定的2個屬性。其中一個是對象的ObservableCollection,稱爲Layers,另一個屬性保存Point,Line或Polygon的枚舉值,稱爲SpatialType。這些將用作地圖應用程序的圖例。我已將圖層綁定到ListBox,沒問題,但在ListBox.ItemTemplate中,我需要將單個變量SpatialType綁定到ListBox中的每個Item。我遇到的問題是,當我嘗試在ListBox內進行綁定時,我所訪問的唯一變量是每個圖層的屬性,而且我無法訪問保存圖層的原始綁定類的任何屬性(和所需的SpatialType屬性)。

我該怎麼做才能在ItemTemplate中綁定信息,而不會搞亂MVVM架構?

回答

0

我最終什麼事用FindAncestor以獲得更高的「梯隊」的DataContext的結合中做:

Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}, Path=DataContext.LayerSymbolization.SpatialType, Mode=TwoWay}" 
0

你可以在你的視圖中有一個ObjectDataProvider,它是你的datacontext的基礎,並且ObjectInstance指向你的viewmodel。然後你可以從ItemTemplate綁定,如下所示:

<UserControl.Resources> 
    <ObjectDataProvider x:Key="Data"/> 
    <DataTemplate x:Key="Template"> 
     <TextBlock Text="{Binding SpatialType,Source={StaticResource Data}}/> 
    </DataTemplate> 
</UserControl.Resources> 
<Grid DataContext={Binding Source={StaticResource Data}}> 
    <ListBox ItemsSource="{Binding Layers}" ItemTemplate="{StaticResource Template}"/> 
</Grid> 

希望這有助於。