什麼其實我最後不得不在VB做:
爲我的自定義命令創建一個新的公共類,因爲它是u無需將我的MainWindow類設置爲Public:
Public Class Commands
Public Shared myCmd As New RoutedCommand
End Class
創建運行所需代碼的Execute和CanExecute方法。
Class MainWindow
Private Sub myCmdCanExecute(ByVal sender As Object, ByVal e As CanExecuteRoutedEventArgs)
e.CanExecute = True
e.Handled = True
End Sub
Private Sub myCmdExecuted(ByVal sender As Object, ByVal e As ExecutedRoutedEventArgs)
//Do stuff here...
e.Handled = True
End Sub
End Class
創建命令在主窗口綁定代碼隱藏和兩個處理方法添加到綁定(這是C#和VB之間完全不同的部分:在後面的主窗口的代碼創建了這兩個方法):
Class MainWindow
Public Sub New()
// This call is required by the designer.
InitializeComponent()
//Add any initialization after the InitializeComponent() call.
//Create command bindings.
Dim cb As New CommandBinding(Commands.myCmd)
AddHandler cb.CanExecute, AddressOf myCmdCanExecute
AddHandler cb.Executed, AddressOf myCmdExecuted
Me.CommandBindings.Add(cb)
End Sub
End Class
將新的自定義命令添加到UserControl上的按鈕對象。使用自定義命令,這在XAML中似乎不可行,所以我必須在代碼隱藏方面做到這一點。所需要的命令類是公共所以命令是在這個用戶控件訪問:
Public Class myUserControl
Public Sub New()
//This call is required by the designer.
InitializeComponent()
// Add any initialization after the InitializeComponent() call.
myButton.Command = Commands.myCmd
End Sub
End Class
Yp,另外404個答案,這次甚至接受! – Rbjz 2016-03-29 10:01:05
我從「The Wayback Machine」互聯網檔案中挖出了文章。不確定最好的辦法是在網站不再存在時避免斷開的鏈接,並且文章的內容太多而無法包含在這裏。 https://web.archive.org/web/20121102095816/http://www.switchonthecode.com/tutorials/wpf-tutorial-command-bindings-and-custom-commands – 2016-03-30 12:59:16
本教程有點太多的閱讀我的胃口。我建議舉個實例。 – Rbjz 2016-03-31 06:52:13