Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot pass/bind command to WPF user control

I'm trying to pass a command to an element in a WPF user control.

<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 the button in the user control is clicked, nothing happens.
When I debug, the Command property is null.
Binding the command to a button outside of the user control does work.
What's going wrong here?

like image 257
David Avatar asked Oct 31 '11 17:10

David


2 Answers

The default DataContext for your Button is your UserControl's DataContext, not your UserControl, so you are trying to bind to DataContext.Command instead of UserControl.Command

To bind to UserControl.Command, use a RelativeSource binding

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

EDIT Just noticed HB's answer, which would also work. Usually I prefer RelativeSource bindings to ElementName ones because sometimes I rename items and used to forget what other controls reference that item by Name

like image 97
Rachel Avatar answered Nov 16 '22 04:11

Rachel


Name the control and use ElementName:

<UserControl ...
             Name="control">
    <Button Command="{Binding Command, ElementName=control}">
    <!-- ... -->
like image 40
H.B. Avatar answered Nov 16 '22 06:11

H.B.