Im attempting to bind a button in a user control to a command defined in my applications main window. Just can't seem to get it to work. The CanExecute method is never called and neither is the code when the button is clicked..
MainWindow.xaml
<Window.CommandBindings>
<CommandBinding x:Name="RefreshCommand"
Command="AppCommands:DataCommands.Refresh"
Executed="Refresh_Executed"
CanExecute="Refresh_CanExecute" />
</Window.CommandBindings>
<uc:Toolbar x:Name="MainToolbar" Grid.Row="0" RefreshCommand="{Binding RefreshCommand}"/>
MainWindow.xaml.cs
private void Refresh_Executed(object sender, ExecutedRoutedEventArgs e)
{
}
private void Refresh_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = false;
}
Additionally this is done in MainWindow's constructor...
MainToolbar.DataContext = this;
Toolbar.xaml
<Button x:Name="btnRefresh" Command="{Binding RefreshCommand, ElementName=ToolbarControl}">Refresh</Button>
Toolbar.xaml.cs
#region Command Bindings public static readonly DependencyProperty RefreshCommandProperty = DependencyProperty.Register("RefreshCommand", typeof(ICommand), typeof(Toolbar), new UIPropertyMetadata(null)); public ICommand RefreshCommand { get { return (ICommand)GetValue(RefreshCommandProperty); } set { SetValue(RefreshCommandProperty, value); } } #endregion
If anyone can see why this doesnt work that would be appreciated. I think Ive got everything hooked up ok. However, I have put breakpoints on my event handlers for the button command in the main window and they just dont get called. The only real area of confusion is in my MainWindow.xaml, am I using the correct binding expression to bind the user controls property to my actual command?
Note: At present the CanExecute is set to false as I want to initially disable the button (but this also doesnt work).
Update: This is clearly the source of the problem...
System.Windows.Data Error: 40 : BindingExpression path error: 'RefreshCommand' property not found on 'object' ''MainWindow' (Name='')'. BindingExpression:Path=RefreshCommand; DataItem='MainWindow' (Name=''); target element is 'Toolbar' (Name='MainToolbar'); target property is 'RefreshCommand' (type 'ICommand')
... but how to fix it?