WPF - Binding a variable in an already bound ListBox?
I really don't know how to title this question, but I need some help with binding to a ListBox.
I have an object, that contains (among other information) 2 properties that need to be bound in one ListBox. One of these is an ObservableCollection of objects, called Layers, and the other property holds an enum value of either Point, Line or Polygon, called SpatialType. These are to act as a legend to a map application. I have bound Layers to a ListBox, no problem, but inside the ListBox.ItemTemplate, I need to bind the single variable SpatialType to every Item in the ListBox. The problem I'm running into is that when I try to bind while inside the ListBox, the only variables I have access to are the properties of each Layer and I can't access any properties of the original bound class that holds the Layers (and the needed SpatialType property).
What can I do to get that piece of information bound inside the Item开发者_C百科Template without messing up a good MVVM architecture?
You can in your view have a ObjectDataProvider that is the basis for your datacontext and have the ObjectInstance point to your viewmodel. Then you can bind from the ItemTemplate like so:
<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>
Hope this helps.
What I ended up doing was using FindAncestor to get the DataContext of a higher "tier" in binding:
Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}, Path=DataContext.LayerSymbolization.SpatialType, Mode=TwoWay}"
精彩评论