Вопрос

I use an Item Template to define how the rows of my grid must be displayed. The grid definition (simplified) shows that the item template source is GridRows (a collection of rows) :

<grid ...>
   (...)
   <ScrollViewer 
          ItemTemplate="{StaticResource GridRowItemDataTemplate}" 
          ItemsSource="{Binding GridRows}" />
   </ScrollViewer>
</grid>

So far, so good.

In the item template, the textbox is bound to ImportZoneName, which resolved of course to GridRows[i].ImportZoneName, and this is exactly what I want :

<DataTemplate x:Key="GridRowItemDataTemplate">
   <Grid>
      <TextBlock {Binding ImportZoneName}" />
      <ComboBox 
           SelectedItem="{Binding SelectedModelingTypeValue}" 
           ItemsSource="{Binding ModelingTypes}" />
   </Grid>
</DataTemplate>

Now the problem : I also want to bind the combo box to an other property (ModelingTypes) of my view model. This property is not linked in any way to GridRows. How can I tell WPF to override (or forget) the item template source?

Many, many thanks !

BTW, I did not find yet a simple guide for these simple binding cases... If anyone have a link to such a guide, I will bless him/her forever :)

Это было полезно?

Решение

You can get the DataContext of the parent list like this:

<DataTemplate x:Key="GridRowItemDataTemplate">
   <Grid>
      <TextBlock {Binding ImportZoneName}" />
      <ComboBox 
           SelectedItem="{Binding SelectedModelingTypeValue}" 
           ItemsSource="{Binding DataContext.ModelingTypes, 
                           RelativeSource={RelativeSource FindAncestor,
                           AncestorType=Grid}}" />
   </Grid>
</DataTemplate>

Replace Grid with the type of the grid you are using (not sure which it is, not evident from the question), as long as its DataContext has the property ModelingTypes

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top