The answer posted by Ed Chapel has one big flaw:
<vm:MyViewModel x:Key="ViewModel" />
causes MyViewModel be built one more time. In normal scenarios, this is undesirable behavior.
By the way, there is an ideal trick to bind to the parent DataContext without restoring the view model.
Assuming MyViewModel has an "ICommand" named TestCommand and is the current DataContext page that contains your UserControl , sets the x:Name page and simply binds the DataContext page to the Tag property of the UserControl using the ElementName binding:
<Page... x:Name="rootPage"> <Grid> <controls:MyUserControl Tag={Binding DataContext, ElementName='rootPage'} ... /> </Grid> ... </Page>
And then in the XAML of your UserControl set x:Name to UserControl and bind your property to the property in Tag :
<UserControl ... x:Name="rootControl"> <Grid> <Button Command={Binding Tag.TestCommand, ElementName='rootControl'} ... /> </Grid> </UserControl>
This may not be the cleanest trick that works, because the Tag property is a dependency property of type object , and you can associate anything with it.
Alexander Zolotaryov
source share