如何将按钮命令绑定到主窗口命令

本文关键字:命令 窗口 绑定 按钮 | 更新日期: 2023-09-27 18:13:41

我试图将用户控件中的按钮绑定到我的应用程序主窗口中定义的命令。就是没法让它工作。CanExecute方法永远不会被调用,当按钮被点击时,代码也不会被调用。

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;
}

另外,这在MainWindow的构造函数中完成…

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

如果有人能看到为什么这不起作用,将不胜感激。我想我已经把一切都接好了。然而,我把断点放在我的事件处理程序的按钮命令在主窗口,他们只是不被调用。唯一真正令人困惑的地方是我的主窗口。xaml,我是否使用正确的绑定表达式将用户控件属性绑定到我的实际命令?

注意:目前CanExecute被设置为false,因为我想最初禁用按钮(但这也不起作用)。

更新:这显然是问题的根源……

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')

…但如何解决呢?

如何将按钮命令绑定到主窗口命令

您的ElementName目标是错误的。

<Button x:Name="btnRefresh" Command="{Binding RefreshCommand, ElementName=ToolbarControl}">Refresh</Button> 
<Button x:Name="btnRefresh" Command="{Binding RefreshCommand, ElementName=MainToolbar}">Refresh</Button> 

ElementName必须是x:Name或Name的值。

——编辑(以上代码指向错误)——

如您所知,在Xaml中的元素到元素交互中,必须定义ElementName。

主窗口中主工具栏的刷新命令。xaml必须绑定到CommandBinding中的x:Name。换句话说,您没有指定元素名称,因此绑定目标指向错误。

试试下面的代码。

<uc:Toolbar x:Name="MainToolbar" Grid.Row="0" RefreshCommand="{Binding ElementName=RefreshCommand, Path=Command}"/>