In MainWindow the commandbinding works fine. In UserControl1 it doesnt work. Note the datacontext is set correctly as is evidenced by the content of the button which is the res
It's the best solution:
Other solutions:
You forgot set DataContext to UserControl1.
public UserControl1()
{
InitializeComponent();
ClickHereCommand = new RoutedCommand();
CommandBindings.Add(new CommandBinding(ClickHereCommand, ClickHereExecuted));
ButtonContent = "Click Here";
this.DataContext = this;
}
And after this you must delete in UserControl1 DataContext in Grid.
This:
you must change to this:
Solution without set DataContext in UserControl:
You must change ButtonContent and ClickHereCommand to DependencyProperty.
public string ButtonContent
{
get { return (string)GetValue(ButtonContentProperty); }
set { SetValue(ButtonContentProperty, value); }
}
public static readonly DependencyProperty ButtonContentProperty =
DependencyProperty.Register("ButtonContent", typeof(string), typeof(UserControl1), new UIPropertyMetadata(string.Empty));
public RoutedCommand ClickHereCommand
{
get { return (RoutedCommand)GetValue(ClickHereCommandProperty); }
set { SetValue(ClickHereCommandProperty, value); }
}
public static readonly DependencyProperty ClickHereCommandProperty =
DependencyProperty.Register("ClickHereCommand", typeof(RoutedCommand), typeof(UserControl1), new UIPropertyMetadata(null));
And in ctor of UserControl1
:
public UserControl1()
{
InitializeComponent();
ClickHereCommand = new RoutedCommand();
CommandBindings.Add(new CommandBinding(ClickHereCommand, ClickHereExecuted));
ButtonContent = "Click Here";
//this.DataContext = this;
}