简体   繁体   English

在VB.net中绑定WPF按钮单击的正确方法是什么

[英]What is the proper way to Bind a WPF button click in VB.net

I am trying to figure out how I should bind the click action of a button in vb.net for WPF 我试图弄清楚如何为WPF绑定vb.net中的按钮单击动作

Here is a section of WPF code 这是WPF代码的一部分

WPF: WPF:

<TabItem Name="tab_emailSender>
    <TextBox Text="{Binding Path=address}" />
    <Button Command="{Binding Path=sendTestMessage}"
</TabItem>

VB VB

Class MainWindow
    Dim thisMessage as new Message

    Private Sub main() Handles Me.Loaded
        tab_emailSender.DataContext = thisMessage
    End Sub
End Class

Class Message
   Public Property address as string

   Public Sub sendTestMessage()
       msgbox("it worked!")
   End Sub
End Class

I am able to bind the textbox's text but I am not sure how to bind the button's click event to the sendTestMessage sub. 我可以绑定文本框的文本,但是不确定如何将按钮的click事件绑定到sendTestMessage子对象。

In order to handle the button's click event, if you want to follow MVVM, you need to create an ICommand property on your ViewModel. 为了处理按钮的click事件,如果要遵循MVVM,则需要在ViewModel上创建ICommand属性。 ICommand is the inteface, so you can do something like this (sorry for C#): ICommand是接口,因此您可以执行以下操作(对C#很抱歉):

public class Message: ICommand
{
    public address { get; set; }


    public bool CanExecute(Object parameter)
    {
        return true; 
    }
    public void Execute(Object parameter)
    {
        //Do the logic here.
    }
}

and the xaml (as far as your DataContext is the instance of Message type): 和xaml(只要您的DataContext是Message类型的实例):

<Button Command="{Binding}" />

Of course you can implement the interface by yourself, on another class, etc. (I've made the implementation inside the Message class because its simplier here), but you can also find useful to use DelegateCommand or RelayCommand . 当然,您可以自己在另一个类等上实现该接口(我已经在Message类内部实现了该实现,因为它在这里更为简单),但是使用DelegateCommandRelayCommand也会发现有用。 This classes will prevent you from re-implementing the interface involved every time you need the new command. 此类将阻止您在每次需要新命令时重新实现所涉及的接口。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM