Cannot pass / bind command to WPF user management.

I am trying to pass a command to an element in a WPF user element.

<UserControl x:Class="MyApp.MyControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <!-- shortened --> <Button Command="{Binding Command}"> <Button.Content> <!-- shortened --> </Button.Content> </Button> </UserControl> 
 public partial class MyControl : UserControl { public static readonly DependencyProperty CommandProperty = DependencyProperty.Register("Command", typeof(ICommand), typeof(MyControl)); //shortened public ICommand Command { get { return (ICommand)GetValue(CommandProperty); } set { SetValue(CommandProperty, value); } } //shortened } 
 <uc:MyControl Command="{Binding DoStuffCommand}" /> <!-- shortened --> 

When you click a button in a user control, nothing happens.
When I debug, the Command property is null.
Binding a command to a button outside the user control works.
What's going on here?

+4
source share
4 answers

By default, the DataContext for your Button is your UserControl DataContext , not your UserControl, so you are trying to bind to DataContext.Command instead of UserControl.Command

To bind to UserControl.Command use the RelativeSource binding

 <Button Command="{Binding Command, RelativeSource={ RelativeSource AncestorType={x:Type local:MyControl}}}"> 

EDIT Just noticed the HB answer , which will also work. I usually prefer RelativeSource bindings to ElementName because sometimes I rename elements and use them to forget that other controls reference this element by name

+8
source

Name the control and use ElementName :

 <UserControl ... Name="control"> <Button Command="{Binding Command, ElementName=control}"> <!-- ... --> 
+5
source

Well, I just get attached to the command from the main control / window. Because the data context will be inherited from it. Something like that.

 <UserControl x:Class="MyApp.MyControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <!-- shortened --> <Button Command="{Binding DoStuffCommand}"> <Button.Content> <!-- shortened --> </Button.Content> </Button> </UserControl> 

You can then remove the dependency property code from the code file.

And remove the binding property of the command,

 <uc:MyControl /> 
0
source

All in all, I always follow Rachel's advice (like the one above). But in this particular case, I would consider installing a DataContext in the root element of a user control, after which it would do a neat binding there.

 <Grid DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}"> <!-- shortened --> <Button Command="{Binding Command}"> <Button.Content> <!-- shortened --> </Button.Content> </Button> </Grid > 
0
source

All Articles