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?
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
Name the control and use ElementName
:
<UserControl ...
Name="control">
<Button Command="{Binding Command, ElementName=control}">
<!-- ... -->
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With