我正在尝试实现命令绑定,以便我的用户可以使用Alt +进行导航。我找到了this示例,但是在形成xmlns和CommandBinding xaml时遇到了问题。
这是我到目前为止所拥有的。我知道它没有正确形成。
xmlns:local="clr-namespace:xxxxx"
<Window.CommandBindings>
<CommandBinding
Command="{x:Static local:xxxxx.ProjectMsg}"
Executed="ProjectMsg"/>
</Window.CommandBindings>
该命令的编码在MainWindow vb:
中Class MainWindow
Public Shared ProjectTab_AltP As New RoutedCommand
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
End Sub
Private Sub MainWindow_Loaded(sender As Object, e As RoutedEventArgs) Handles Me.Loaded
ProjectTab_AltP.InputGestures.Add(New KeyGesture(Key.P, ModifierKeys.Control))
Me.CommandBindings.Add(New CommandBinding(ProjectTab_AltP, AddressOf Me.ProjectMsg))
End Sub
Private Sub ProjectMsg(sender As Object, e As ExecutedRoutedEventArgs)
MessageBox.Show("hi")
End Sub
我收到名称“xxxxx”在名称空间clr-namespace:xxxxx中不存在的错误。
在主窗口vb中,没有声明名称空间。如果我尝试添加一个错误,会发生许多错误。
我必须在主窗口vb中有一个命名空间吗?
我是wpf的菜鸟,所以我很感激任何帮助或建议。谢谢。
答案 0 :(得分:1)
我必须在主窗口vb中有一个命名空间吗?
没有。在Visual Studio中的Project-&gt; Properties-&gt; Application-&gt; Root命名空间下检查应用程序的根命名空间。默认情况下,它与应用程序的名称相同,例如“WpfApplication1”:
xmlns:local="clr-namespace:WpfApplication1"
您还应该通过属性:
公开命令Public Shared ReadOnly Property ProjectTab_AltP() As RoutedUICommand = New RoutedUICommand()
<Window.CommandBindings>
<CommandBinding
Command="{x:Static local:MainWindow.ProjectTab_AltP}"
Executed="ProjectMsg"/>
</Window.CommandBindings>
答案 1 :(得分:0)
local
是VB名称空间xxxxx
的别名。 xxxxx
中是否包含xxxxx
?不,它本身并不包含在内。 local:xxxxx
最多只能表示xxxxx.xxxxx
之类的内容,但您无法在其中添加名称空间。
绑定到静态命令属性的正确方法如下:
Command="{x:Static local:WhateverClassName.StaticCommandProperty}"
什么是静态命令属性?
它是一个返回命令的静态属性。命令是实现接口System.Windows.Input.ICommand
的任何对象。 ProjectMsg
不是这样的。这是一种方法。
请参阅mm8关于如何通过该路线解决问题的出色答案。
下面是一种更纯粹的XAML方法。
我认为你在MainWindow_Loaded
中创建的命令绑定是正常的,但是尝试在XAML中对这些内容进行评论并执行此操作。 VB中使用的仅 的东西是你的ProjectMsg()
执行处理程序方法。
<Window.Resources>
<!-- Create a command object. -->
<RoutedUICommand
x:Key="ProjectMsgCmdResource"
/>
</Window.Resources>
<Window.CommandBindings>
<!-- Bind the command object to your command execute method. -->
<CommandBinding
Command="{StaticResource ProjectMsgCmdResource}"
Executed="ProjectMsg"
/>
</Window.CommandBindings>
<Window.InputBindings>
<!-- And bind a key input binding to your command. -->
<KeyBinding
Key="P"
Modifiers="Ctrl"
Command="{StaticResource ProjectMsgCmdResource}"
/>
</Window.InputBindings>