I am working through the sample code available in the Prism Github repo and I am confused about a particular line.
<Style TargetType="TabItem">
<Setter Property="Header" Value="{Binding DataContext.Title}" />
</Style>
Why does the Binding have to specify the DataContext
property? My understanding is the binding source by default is the DataContext
for elements. Is it because it is in a style? It seems like the binding source here is the TabItem
and you have to access the DataContext property explicitly.
Binding is not relative to the TargetType of the style. Binding path is resolved against current DataContext of FrameworkElement after Style is applied (unless something changes Source, like explicit setting Source, or RelativeSource, or ElementName).
what happens here it that Prism RegionManager uses ViewA/ViewB as DataContexts for TabItems. Confirm it with the following code:
<TabControl prism:RegionManager.RegionName="ContentRegion" Margin="5"
SelectionChanged="TabControl_SelectionChanged"/>
private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var tabControl = (TabControl)sender;
var idx = tabControl.SelectedIndex;
if (idx >= 0)
{
var item = tabControl.ItemContainerGenerator.ContainerFromIndex(idx) as TabItem;
var dc = item.DataContext; // ViewA or ViewB
}
}
ViewA/ViewB are controls, and have their own DataContext (corresponding view models). TabItem Header binds to property in nested DataContexts, that is why DataContext
is present in binding path