Josh Smith's legendary article: I need a bit more on the DataBinding that takes place

前提是你 提交于 2019-12-06 04:22:56

The syntax ItemsSource="{Binding}" should bind the ItemsSource directly to the TabControl’s DataContext, rather than to any of the DataContext’s properties. But where exactly is the TabControl’s DataContext being set?

By virtue of being a data template, the TabControl will have its DataContext set (by WPF) to the data item it is templating. In fact, the root-level item in the data template will have its DataContext set by WPF. In this case, it's a TabControl.

Since the data template is assigned to the ContentControl's ContentTemplate property, it will automatically receive the ContentControl's Content as its DataContext.

How exactly is Content="{Binding Path=Workspaces}" creating a binding between ItemsSource of the TabControl and the Workspaces (the ObservableCollection of WorkspaceViewModel)?

I think my previous answer addresses this, but let me re-state it in a form that directly answers this question. The binding on the ContentControl ensures that the DataContext for the DataTemplate is set to the workspace collection. Thus, the TabControl can bind to the workspace collection by specifying a Binding without a Path.

The article says By relying on data binding, the Content property of a TabItem receives a ViewModelBase-derived object to display. How ?!? Ok, through data binding. But that is just too much to abstract away, for me.

Again, this comes down to WPF automatically assigning the correct object as the data context of the generated item (a TabItem in this case). When an ItemsControl (such as TabControl) is bound to a collection, it generates a container (a TabItem in this case) for each item in the bound collection. The container automatically receives the data item (a workspace view model in this case) as its data context.

"But where exactly is the TabControl’s DataContext being set?" Workspaces is the DataContext and so the Itemssource for the TabControl.

<ContentControl Content="{Binding Path=Workspaces}" ContentTemplate="{StaticResource ResourceKey=WorkspacesTemplate}"/>

"How exactly is Content="{Binding Path=Workspaces}" creating a binding between ItemsSource of the TabControl and the Workspaces (the ObservableCollection of WorkspaceViewModel)?" Workspaces are the DataContext for the DataTemplate/TabControl and the ItemsSource is set to the DataContext.

 <TabControl Margin="4" ItemsSource="{Binding}"

"The article says By relying on data binding, the Content property of a TabItem receives a ViewModelBase-derived object to display. How ?!?" i dont know the article, but i assume that Workspaces is a collection of object derived from ViewModelBase. every tabitem represent on item from the collection and so a viewmodelbase-derived object.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!