2010-06-11 89 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> 

希望这有助于。