我正在网上做一些研究,以了解如何做到这一点,但到目前为止我还没有做到。我认为我必须克服知识差距。
我有一个wpf按钮,当点击它时会执行它绑定的对象内部。
我想知道如何让按钮执行exampleObject.displayMessage()。
Private Sub Window_Loaded(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
Dim exObject As New exampleObject
Grid1.DataContext = exObject
End Sub
Public Class exampleObject
Public ReadOnly Property testMessage As String
Get
Return "this is a test"
End Get
End Property
Public Sub displayMessage()
MsgBox(testMessage)
End Sub
End Class
<Window x:Class="Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
<Grid Name="Grid1">
<Button Content="Button" Name="Button1"/>
</Grid>
</Grid>
</Window>
答案 0 :(得分:0)
要执行方法,您需要使用命令。请参阅以下实施。
<Grid>
<Grid>
<Grid Name="Grid1">
<Button Content="Button" Name="Button1" Command="{Binding TestCommand}"/>
</Grid>
</Grid>
</Grid>
Class MainWindow
Private Sub Window_Loaded(sender As Object, e As RoutedEventArgs)
Dim exObject As New exampleObject
Grid1.DataContext = exObject
End Sub
End Class
Public Class exampleObject
Private m_TestCommand As ICommand
Public Property TestCommand As ICommand
Get
Return m_TestCommand
End Get
Set(ByVal value As ICommand)
m_TestCommand = value
End Set
End Property
Public Sub New()
m_TestCommand = New DelegateCommand(AddressOf displayMessage, AddressOf CandisplayMessage)
End Sub
Public Sub displayMessage(ByVal param As Object)
MsgBox(testMessage)
End Sub
Private Function CandisplayMessage(ByVal param As Object) As Boolean
Return True
End Function
Public ReadOnly Property testMessage As String
Get
Return "this is a test"
End Get
End Property
End Class
Public Class DelegateCommand
Implements ICommand
Private m_canExecute As Func(Of Object, Boolean)
Private m_executeAction As Action(Of Object)
Private m_canExecuteCache As Boolean
Public Event CanExecuteChanged(ByVal sender As Object, ByVal e As System.EventArgs) Implements ICommand.CanExecuteChanged
Public Sub New(ByVal executeAction As Action(Of Object), ByVal canExecute As Func(Of Object, Boolean))
Me.m_executeAction = executeAction
Me.m_canExecute = canExecute
End Sub
Public Function CanExecute(ByVal parameter As Object) As Boolean Implements ICommand.CanExecute
Dim temp As Boolean = m_canExecute(parameter)
If m_canExecuteCache <> temp Then
m_canExecuteCache = temp
RaiseEvent CanExecuteChanged(Me, New EventArgs())
End If
Return m_canExecuteCache
End Function
Public Sub Execute(ByVal parameter As Object) Implements ICommand.Execute
m_executeAction(parameter)
End Sub
End Class
我从http://www.paulspatterson.com/mvvm-and-wpf-for-vb-net-%E2%80%93-part-5-%E2%80%93-delegating-commands/获得了委托命令。该网站提供了非常详细的信息。