简体   繁体   中英

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

I have some problems about datacontext binding.

My app has virtualization listbox.

Sometimes Button is not fired dataContextChanged.

So I found this.

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

My Code is first one. but It's not fired DataContextChanged sometimes, So I changed code to second one.

snoop said first one is from inherit, and second one is from parentTemplate.

What is different first one and second one?

TL;DR:

SomeProperty={Binding} will bind the SomeProperty to the ENTIRE DataContext object from the parent. SomeProperty does not have to be the DataContext from the child. In this special case I don't think there is any difference, since the DataContext is inherited anyways. You are simply explicitly stating, what is already the default. Discussed here

More Info:

Here is an explanation from the official documentation for

 <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 .

and from 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.)

In general, the DataContext is inherited from parent elements. So in your 2nd example the button gets the DataContext from the Grid. Example

"ItemsControl" are special: Example

I don't know what ~~ is, is this meant to be a placeholder?

Some more information on Bindings and Markup Extensions: Link1 Link2 Link3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM