0

I have a window that is created at runtime that contains a UserControl. That UserControl has a reference to a command on the window:

...
<Button>
   Command="{Binding DataContext.ReturnCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type views:EditCartView}}, Mode=OneWay}"
</Button>
...

This works as expected, when the button is clicked, the command is called from the EditCartView window ViewModel. But I was wondering is it possible to call the same command using ElementName? Something like this:

<Button>
   Command="{Binding DataContext.ReturnCommand, ElementName=EditCartWindow, Mode=OneWay}"
</Button>

and with setting the name on the window:

<Window x:Class="Views.EditCartView"
   Name="EditCartWindow"
...

I have tried calling RegisterName("EditCartWindow", this); in the EditCartView constructor with no luck. Thank you for your help.

NKatic
  • 17
  • 1
  • 4
  • How Is the datacontext of the usercontrol set? If it is derived from the parent, you should just be able to call the command directly. I.E. {Binding ReturnCommand} – Kevin Cook Apr 08 '19 at 11:30
  • @KevinCook It's not derived from the parent, the UserControl content is wrapped in a border that has Binding ElementName=ArticleItemEditUserControl set. And the UserControl has the name property set to the same name. – NKatic Apr 08 '19 at 11:37
  • Try using a BindingProxy, here is a link: https://thomaslevesque.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-inherited/ – Kevin Cook Apr 08 '19 at 11:49
  • Here is a similar question here: https://stackoverflow.com/questions/6575180/how-to-access-parents-datacontext-from-a-usercontrol – Kevin Cook Apr 08 '19 at 11:52
  • @KevinCook Thank you for your help. Unfortunately BindingProxy doesn't apply in this situation because I can't set its binding since I'm working with multiple xaml files and I can't reference the Binding properly. Regarding the other link, it enforced the idea I already had which is passing the delegate to the UserControl from VM of the window. But I'd like to avoid passing too many references around to keep the coupling to minimum. If it's possible to solve the problem with the cunning use of (mostly) xaml that'd be great, if not I can accept that answer as the correct one. – NKatic Apr 08 '19 at 12:23
  • You could try x:reference. Roughly "{Binding Source={x:Reference EditCardWindow}, Path=DataContext.ReturnCommand}". Or you could make your viewmodel a resource of the window and then it'll be in scope for anything inside that window. – Andy Apr 08 '19 at 12:37

0 Answers0