简体   繁体   中英

Is it possible in wpf to implicitly bind the data context of the usercontrol when using content control with data template?

Right now the only thing exist is a control template with data template.

<ContentControl Grid.Row="1" Content="{Binding CurrentVM,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">
  <ContentControl.Resources>
    <DataTemplate DataType="{x:Type ViewModels:HomeVM}">
      <Views:Home />
    </DataTemplate>
  </ContentControl.Resources>
</ContentControl>

In my views:home I didn't set the data context to my homeviewmodel class but when I bind a property on my button to a property of my homeviewmodel it just works like magic, can someone explain this sorcery?

can someone explain this sorcery?

For binding, the initial control's DataContext is examined. If it is not null, the binding is attempted at that point for the property specified. If the DataContext is null (not that the binding failed mind you), then control's parent's DataContext is looked at and the same happens. That process continues until the main page's DataContext is finally looked at.

Somewhere in your chain, a parent's context was non null with the VM, you have set, and your other control/situation appeared to work without having to do anything for that control and it bound itself to the property of the object held in the DataContext .

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