{binding} 和 wpf datacontext 中的 inherit 有什么不同?

What is different between {binding} and inherit in wpf datacontext?

我有一些关于数据上下文绑定的问题。

我的应用程序有虚拟化列表框。

有时按钮不会触发 dataContextChanged。

所以我找到了这个。

<Grid DataContext={Binding ~~>
  <Button DataContext={Binding}/>
 </Grid>
 <Grid DataContext={Binding ~~>
  <Button/>
 </Grid>

我的代码是第一个。但它有时不会触发 DataContextChanged,所以我将代码更改为第二个。

snoop说第一个是inherit,第二个是parentTemplate。

第一个和第二个有什么不同?

长话短说:

SomeProperty={Binding} 会将 SomeProperty 绑定到父级的整个 DataContext 对象。 SomeProperty 不必是子项的 DataContext。在这种特殊情况下,我认为没有任何区别,因为 DataContext 无论如何都是继承的。您只是明确说明,什么已经是默认值。 Discussed here

更多信息:

这是official documentation

的解释
 <Button DataContext={Binding}/>

As long as the binding already has a data context (for example, the inherited data context coming from a parent element), and whatever item or collection being returned by that context is appropriate for binding without requiring further path modification, a binding declaration can have no clauses at all: {Binding}. This is often the way a binding is specified for data styling, where the binding acts upon a collection. For more information, see Using Entire Objects as a Binding Source.

来自here

<ListBox ItemsSource="{Binding}"
         IsSynchronizedWithCurrentItem="true"/>

The above example uses the empty binding syntax: {Binding}. In this case, the ListBox inherits the DataContext from a parent DockPanel element (not shown in this example). When the path is not specified, the default is to bind to the entire object. In other words, in this example, the path has been left out because we are binding the ItemsSource property to the entire object. (See the Binding to collections section for an in-depth discussion.)

一般来说,DataContext 是从父元素继承的。因此,在您的第二个示例中,按钮从 Grid 获取 DataContext。 Example

“ItemsControl”比较特殊:Example

我不知道 ~~ 是什么,这是一个占位符吗?

有关绑定和标记扩展的更多信息: Link1 Link2 Link3