Search code examples
c#wpfdata-bindingelementname

WPF ElementName not initialized in time


In my MVVM model I have named a UserControl like:

x:Name="root"

In my viewmodel have a bool called AllChecked and as the name indicates this should be bound to a checkbox in the xaml file indicating whether all rows in a datagrid should be checked or unchecked.

In my xaml file I have a datagrid like:

    <DataGrid  ItemsSource="{Binding SomeObservableCollection, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
        <DataGrid.Columns>
            <DataGridCheckBoxColumn Binding="{Binding IsSelected, UpdateSourceTrigger=PropertyChanged}"
                <DataGridCheckBoxColumn.Header>
                    <CheckBox IsChecked="{Binding DataContext.AllChecked, ElementName=root, Mode=TwoWay}" HorizontalAlignment="Center"/>
                </DataGridCheckBoxColumn.Header>
            </DataGridCheckBoxColumn>
            <DataGridTextColumn Header="Column A" Binding="{Binding Path=a}" Width="120" IsReadOnly="true"/>
            <DataGridTextColumn Header="Column B" Binding="{Binding Path=b, StringFormat=dd-MM-yyyy}" Width="120" IsReadOnly="true"/>
            <DataGridTextColumn Header="Column C" Binding="{Binding Path=c}" Width="90" IsReadOnly="true"/>
            <DataGridTextColumn Header="Column D" Binding="{Binding Path=d}" IsReadOnly="true" Width="130" />
        </DataGrid.Columns>
    </DataGrid>

When I start the application the binding of AllChecked does not work, the error being that

"Cannot find source: ElementName = root"

If I delete root from ElementName and rewrite it again, it suddenly works. I have no idea what is going on, but it seems like some kind of timing issue where the binding is set before the x:Name of the UserControl is defined, maybe?

Anyone able to help here?


Solution

  • The column does not belong to the logical tree of the DataGrid. So WPF doesn't know where to get the DataContext. The typical solution to this problem is something called a BindingProxy. Read this:

    https://thomaslevesque.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-inherited/