views:

28

answers:

1

I have some problem to access the Window's DataContext from within a DataGrid.

The DataGrid is bound to a IBindingList:

public IBindingList Items{ get; set; }
    private void initItems()
    {
        //ItemFactory is a Linq2SQL Context, Items is the view of availabe Items
        this.Items = this.ItemFactory.Items.GetNewBindingList();
    }

From within my xaml I try to get those data to fill a ComboBox:

 <DataGridComboBoxColumn Header="Typ" 
                             DisplayMemberPath="Description"
                             SelectedValuePath="ItemID"      
                             ItemsSource="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}, Mode=OneWay, Path=DataContext.Items, UpdateSourceTrigger=PropertyChanged}" />

But it doesn't work. I tried out many variants already. The ComboBox gets not populated.
Any help greatly appreciated!

Note:

The following ComboBox in the same Window does work:

<ComboBox x:Name="workingCombo" ItemsSource="{Binding Path=Items}" DisplayMemberPath="Description" SelectedValuePath="ItemID" />
+1  A: 

The DataGridComboBoxColumn is not directly connected to the visual tree and therefore the FindAncestor-operation will fail (and also the DataContext will not be inherited).

  • The most simple solution is to create a ViewModel for each line and provide there in the ItemsSource for the ComboBox.
  • Using a DataGridTemplateColumn and placing the ComboBox in the DataTemplate helps.
  • Here is a another post concerning this problem. And look also at this post.
HCL
Thank you for this good answer! I didn't find those 2 posts by googling. - The problem about using a ViewModel for each row is that I bind the BindingList directly to the DataGrid's ItemSource.- If I have to use a DataGridTemplateColumn.. what's a DataGridComboBoxColumn worth?..guess one can only use it with static defined collections then.I'll try this out at work tomorrow and then mark it as answer when I succeed ;) ty again
SwissCoder
It worked using the RelativePath when I use a ComboBox in a DataGridTemplateColumn
SwissCoder