Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Databinding to a Parent datacontext in XAML

Tags:

wpf

xaml

The user control into which those 2 elements live has a property called ColumnTypes.

Each of those elements refer relatively with the same expression to the main datacontext, yet the first one does not work, while the latter does.

Do you have any idea how to investigate that ?

<DataGrid  x:Name="DataGrid" AutoGenerateColumns="False" ItemsSource="{Binding Table}"  >
    <DataGrid.Columns>
            <DataGridComboBoxColumn  Header="Type"   >
                <DataGridComboBoxColumn.ItemsSource>
                    <Binding Path="DataContext.GetColumnTypes"   RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type UserControl}}" />
                </DataGridComboBoxColumn.ItemsSource>
            </DataGridComboBoxColumn>
    </DataGrid.Columns>
</DataGrid>
<ComboBox Grid.Row="1">
    <ComboBox.ItemsSource>
        <Binding Path="DataContext.GetColumnTypes"   RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type UserControl}}" />
    </ComboBox.ItemsSource>
</ComboBox>

System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.UserControl', AncestorLevel='1''. BindingExpression:Path=DataContext.GetColumnTypes; DataItem=null; target element is 'DataGridComboBoxColumn' (HashCode=53813616); target property is 'ItemsSource' (type 'IEnumerable')

like image 704
nicolas Avatar asked Dec 20 '22 07:12

nicolas


1 Answers

This is a known limitation of the DataGridComboBoxColumn.

You can see on MSDN what kind of things you can bind to its ItemsSource property. A regular property is not one of them, so your case wont work.

A different way to achieve what you want, is to make a DataGridTemplateColumn which contains a ComboBox.

In your case that would look something like this:

<DataGrid.Columns>
    <DataGridTemplateColumn Header="Type">
        <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <ComboBox ItemsSource="{Binding DataContext.GetColumnTypes, 
                        RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}" />
            </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
</DataGrid.Columns>
like image 133
Peter Hansen Avatar answered Jan 06 '23 08:01

Peter Hansen