I'm trying to use a single DataGrid as the content for each tab in a tab control (I'll then reload the contents of the grid, to show models at different statuses when clicking on different tabs).
However, for some reason the DataGrid fails to bind when it is inside the DataTemplate of the TabControl. The same Datagrid XAML, and binding works perfectly when in the main flow of the page however.
<!-- first grid works perfectly-->
<DataGrid ItemsSource="{Binding RANsToDisplay}" />
<TabControl>
<TabControl.ContentTemplate>
<DataTemplate>
<!-- Second grid fails to bind-->
<DataGrid ItemsSource="{Binding RANsToDisplay}" />
</DataTemplate>
</TabControl.ContentTemplate>
<TabItem Header="Calls"></TabItem>
<TabItem Header="Collections"></TabItem>
<TabItem Header="Receipts"></TabItem>
</TabControl>
I guess it's because the DataContext of items in a Tab Control's DataTemplate is different compared to items outside it, but I'm only just getting my WPF head back on after a long break, and am not sure how to get the DataGrid in the DataTemplate to bind properly to the DataContext.
Many thanks in advance for any help / pointers.
You need to use a relative path for the DataGrid Binding;
<!-- first grid works perfectly-->
<DataGrid ItemsSource="{Binding RANsToDisplay}" />
<TabControl>
<TabControl.ContentTemplate>
<DataTemplate>
<!-- Second grid fails to bind-->
<DataGrid ItemsSource="{Binding DataContext.RANsToDisplay, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}" />
</DataTemplate>
</TabControl.ContentTemplate>
<TabItem Header="Calls"></TabItem>
<TabItem Header="Collections"></TabItem>
<TabItem Header="Receipts"></TabItem>
</TabControl>
Just change UserControl to whatever your control is that houses your DataContext