wpf 如何以编程方式使用 EventTrigger 和 InvokeCommandAction?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14372759/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 07:05:07  来源:igfitidea点击:

How to use EventTrigger and InvokeCommandAction programmatically?

wpfmvvm

提问by Brandon Moore

I have a popup with a TextBoxthat the user should enter a ticket number into, and then when the user presses the enter key I want the ticket number to be passed to the ViewModel which will retrieve the ticket.

我有一个弹出窗口,TextBox用户应该在其中输入一个票号,然后当用户按下回车键时,我希望将票号传递给将检索票证的 ViewModel。

Here's the xaml for the TextBox:

这是用于的 xaml TextBox

<TextBox x:Name="TicketNumber">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="KeyDown">
            <i:InvokeCommandAction Command="{Binding OpenTicketCommand}" 
                                   CommandParameter="{Binding ElementName=TicketNumber,
                                                              Path=Text}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</TextBox>

The above works on any keypress, but I really only want it to happen when the enter key is pressed. How would I go about doing that?

以上适用于任何按键,但我真的只希望它在按下回车键时发生。我该怎么做呢?

EDIT:I am assuming it would have to be done programmatically (hence the title), but if not that's okay too.

编辑:我假设它必须以编程方式完成(因此标题),但如果不是,那也没关系。

回答by Adrian Faciu

You could use InputBindings - KeyBindingas alternative approach.

您可以将其InputBindings - KeyBinding用作替代方法。

Something like this:

像这样的东西:

<TextBox x:Name="TicketNumber">
    <TextBox.InputBindings>
        <KeyBinding Key="Enter"
                    Command="{Binding OpenTicketCommand}" 
                    CommandParameter="{Binding ElementName=TicketNumber,
                                               Path=Text}"/>
    </TextBox.InputBindings>
</TextBox>