wpf DataContext="{Binding}" 是什么意思?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13968321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does DataContext="{Binding}" mean?
提问by Ivan Prodanov
I'm trying to find out where the items in a HeaderedContentControl come from in a project that's not mine. Here's the code:
我试图找出 HeaderedContentControl 中的项目来自不是我的项目的哪里。这是代码:
<HeaderedContentControl
Content="{Binding Path=Workspaces}"
ContentTemplate="{StaticResource WorkspacesTemplate}"
Header="Workspaces"
Style="{StaticResource MainHCCStyle}"
DataContext="{Binding}" // <--- this
/>
<DataTemplate x:Key="WorkspacesTemplate">
<TabControl
IsSynchronizedWithCurrentItem="True"
ItemsSource="{Binding}"
ItemTemplate="{StaticResource ClosableTabItemTemplate}"
Margin="4"
/>
so let's examine it:
所以让我们检查一下:
- ContentTemplate attribute describes how the items are desplayed.
- WorkspacesTemplate sets ItemsSource's attribute to {Binding} meaning it's bound to its DataContext property (DataContext of HeaderedContentControl)
- So I look at HeaderedContentControl's dataContext, but it is described as "{Binding}" as well...
- ContentTemplate 属性描述了项目的显示方式。
- WorkspacesTemplate 将 ItemsSource 的属性设置为 {Binding} 意味着它绑定到它的 DataContext 属性(HeaderedContentControl 的 DataContext)
- 所以我查看了 HeaderedContentControl 的 dataContext,但它也被描述为“{Binding}”......
What does that mean?
这意味着什么?
回答by Steve Greatrex
Without seeing more of your code it is hard to be certain, but DataContext="{Binding}"is quite often unnecessary, as any object in the current binding context will automatically have its DataContextproperty set to the equivalent of {Binding}.
如果没有看到更多代码,很难确定,但DataContext="{Binding}"通常是不必要的,因为当前绑定上下文中的任何对象都会自动将其DataContext属性设置为等效于{Binding}.
Remember:
记住:
Property="{Binding}"means "setthis.Propertyto the evaluated value ofthis.DataContext"Property="{Binding Path=SubProperty}"means "setthis.Propertyto the evaluated value ofthis.DataContext.SubProperty"- etc
Property="{Binding}"装置“设置this.Property到的评价值this.DataContext”Property="{Binding Path=SubProperty}"装置“设置this.Property到的评价值this.DataContext.SubProperty”- 等等
This means that DataContext="{Binding}"means "set this.DataContextto the evaluated value of this.DataContext", which (in most cases) is redundant!
这意味着DataContext="{Binding}"“设置this.DataContext为”的评估值this.DataContext,这(在大多数情况下)是多余的!
回答by Jozef Cechovsky
{Binding}is something like bind 'this' or current data context - assigned or inherited from parents. For better understanding, equivalent for {Binding}is {Binding .}or {Binding Path=.}
{Binding}类似于绑定“this”或当前数据上下文 - 从父项分配或继承。为了更好地理解,等效于{Binding}is{Binding .}或{Binding Path=.}

