wpf如何在命令绑定中找到ApplicationCommands?

时间:2013-09-13 23:47:21

标签: c# wpf xaml

我对命令绑定如何知道applicationcommands的位置感到困惑。它不是包含命令绑定的控件的属性,因此xaml解析器只是查找层次结构直到找到它?

如果是这种情况,那么如果我将所有命令放入app类中,它们是否也会自动找到?最终这就是我所希望的。我只是想知道在哪里制作我的命令,以便可以从xaml轻松访问它们

  <UserControl.CommandBindings>
    <CommandBinding Command="ApplicationCommands.Properties"
                    Executed="EditPreferencesExecuted"
                    CanExecute="CanAlwaysExecute"/>
   </UserControl.CommandBindings>

1 个答案:

答案 0 :(得分:1)

它是内置的。在设计自己的命令时,必须在控件的声明标记中包含命名空间,然后使用您选择的命名空间标记引用命名空间和命令。

以下是我的UserControl中使用Helix 3D Toolkit库的示例。在控制声明中,我包括:

<dxr:DXRibbonWindow 
x:Class="Shell" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
[etc...]
xmlns:h="clr-namespace:HelixToolkit.Wpf;assembly=HelixToolkit.Wpf" 

使用在该命名空间中实现的命令,然后只需要像这样声明它们:

        <Button Content="Left View" 
         Command="{x:Static h:CameraController.LeftViewCommand}" />

库中的h:CameraController类定义了一个处理命令的静态ICommand属性:

    public static RoutedCommand LeftViewCommand = new RoutedCommand();

在该类的构造函数中是这段代码:

        this.CommandBindings.Add(new CommandBinding(LeftViewCommand, this.LeftViewHandler));

...为XAML系统提供基于实例的绑定。在你的CommandBindings XAML片段中,它看起来像这样:

<UserControl.CommandBindings>
    <CommandBinding Command="h:CameraController.LeftViewCommand"
                    Executed="SomeExecuteMethodInCodeBehind"
                    CanExecute="SomeExecuteTestInCodeBehind"/>
   </UserControl.CommandBindings>

因此,要总结回答您的问题,您必须将命令放在命名空间中,在XAML标记中引用命名空间,并在代码或XAML声明中提供绑定。

相关问题