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

时间:2011-11-06 11:03:46

标签: c# wpf user-controls wpf-controls dependency-properties

我试图将用户控件中的按钮绑定到我的应用程序主窗口中定义的命令。似乎无法让它发挥作用。永远不会调用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

如果有人能够理解为什么这不起作用,那将是值得赞赏的。我想我已经把所有东西搞定了。但是,我已经在主窗口中为按钮命令的事件处理程序添加了断点,并且它们不会被调用。唯一真正的混淆区域是在我的MainWindow.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')

...但是如何解决?

1 个答案:

答案 0 :(得分:1)

您的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的值:名称或名称。

- 编辑(错误指出上述代码) -

如您所知,在Xaml中的Element-to-Element交互中,必须定义ElementName。

MainWindow.xaml中MainToolbar的RefreshCommand必须在CommandBinding中绑定到x:Name。 换句话说,您没有指定元素名称,因此错误地指出了绑定目标。

尝试以下代码。

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