简体   繁体   English

C#WPF-如何将文本框的Enter键绑定到方法?

[英]C# WPF - How to Bind TextBox Enter Key Press to a Method?

I have a TextBox with an 'OK' button below it. 我有一个TextBox ,下面有一个“确定”按钮。 The 'OK' button runs the method in my RunPanel static class like this: RunPanel.RunOK(); “确定”按钮可以像下面这样在我的RunPanel静态类中运行该方法: RunPanel.RunOK(); .

I would like pressing enter in the TextBox to also execute the method RunPanel.RunOK() . 我想在TextBoxEnter也可以执行方法RunPanel.RunOK()

How could I do this in XAML? 如何在XAML中做到这一点?

The answers I have come across seem confusing, so I was wondering if someone could help me out. 我遇到的答案似乎令人困惑,所以我想知道是否有人可以帮助我。

private void textBox_KeyUp(object sender, KeyEventArgs e)
    {
       if(e.Key == Key.Return)
        {
            MessageBox.Show("Enter key pressed, put your method in here!");
        }
    }

This does not help you execute the method you specified in XAML, however having the textbox subscribe to a KeyUp event, and then performing a check on which key was entered solves your issue. 这不能帮助您执行XAML中指定的方法,但是让文本框订阅KeyUp事件,然后检查输入的密钥可以解决您的问题。 You can put RunPanel.RunOK() inside the if statement in this case, and it will fire IF the enter key was pressed inside the textbox. 在这种情况下,可以将RunPanel.RunOK()放在if语句中,如果在文本框中按下回车键,它将触发。

KeyBinding would be probably your best shot. KeyBinding可能是您最好的选择。

For instance: 例如:

<Window>
   <Window.InputBindings>
    <KeyBinding Command="{Binding SomeCommand, RelativeSource={RelativeSource Self}}" Modifiers="Control" Key="F5"></KeyBinding>
   </Window.InputBindings>
 </Window>

How could I do this in XAML? 如何在XAML中做到这一点?

XAML is a markup language and you cannot really call methods in it. XAML是一种标记语言,您不能真正在其中调用方法。 You could bind to a method using an ObjectDataProvider as described here: http://www.devcurry.com/2011/03/wpf-4-using-objectdataprovider-for.html 您可以按如下所述使用ObjectDataProvider绑定到方法: http : //www.devcurry.com/2011/03/wpf-4-using-objectdataprovider-for.html

But if you want to do something when a button is clicked you should bind to a command of a view model and call your static method in the Execute method of this command. 但是,如果要在单击按钮时执行某些操作,则应绑定到视图模型的命令,并在此命令的Execute方法中调用您的静态方法。

Trying to everything or as much as possible in XAML just because you can and just for the sake of eliminating code is generally considered as an anti-pattern. 仅仅因为可以并且为了消除代码而尝试在XAML中进行所有事情或尽可能多的尝试,通常被认为是一种反模式。

MVVM is not about eliminating code, it's mainly about separation of concerns and C# is a much more expressive and more concise language than XAML. MVVM并不是要消除代码,主要是要分离关注点,并且C#是比XAML更具表达力和简洁性的语言。 So you should implement the behaviour of your application using a programming such as C# language and use XAML to define the visual presentation and the layout of your UI. 因此,您应该使用诸如C#语言之类的程序来实现应用程序的行为,并使用XAML定义用户界面的视觉表示和布局。

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

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