如何在命令wpf中传递文本框KeyEventArgs和textbox值

问题描述 投票:0回答:1

我正在努力解决像我有一个文本框的问题

<TextBox Name="FilterInputText" Visibility="{Binding VisibiltyAttr}" Width="500" Height="30" Text="{Binding InputText}" HorizontalAlignment="Left" Margin="5">
                    <TextBox.InputBindings>
                        <KeyBinding Command="{Binding EnterCommand}" Key="Enter" />
                        <KeyBinding Command="{Binding DownSelectionCommand}" Key="Down" />
                    </TextBox.InputBindings>
                    <i:Interaction.Triggers>
                        <i:EventTrigger EventName="KeyUp">
                            <i:InvokeCommandAction  Command="{Binding CompleteCommand}"  CommandParameter="{Binding Text, ElementName=InputText}" />
                        </i:EventTrigger>
                    </i:Interaction.Triggers>
                </TextBox> 

我在这里触发了一个带有“KeyUp”事件的文本框输入内容的事件。现在我正在为自动完成文本框工作,所以我显示了在列表框中输入正常工作的建议。所以我需要绑定键与此文本框绑定,以便在显示建议后,用户可以按下键并从那里选择他想要的选项。对于向下键的键绑定,它可以正常工作。

问题在于事件密钥,因为在文本框中按任何键然后触发此事件。现在我发送文本框值作为命令参数,但我还需要发送带有comamnd pararmter的keyeventargs,以便我可以找到按下哪个键,并且当按下键时,我将不再执行该方法。

那么我怎么能把textbox值和keyeventargs作为命令参数传递,我严格遵循mvvm模式。

wpf mvvm prism keyboard-events
1个回答
0
投票

默认情况下,如果未指定命令参数,则InvokeCommandAction将传递事件参数。此外,您的文本框绑定到视图模型上的属性。因此,如果您更改代码如下:

<TextBox Name="FilterInputText" Visibility="{Binding VisibiltyAttr}" Width="500" Height="30" Text="{Binding InputText, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" Margin="5">
  <TextBox.InputBindings>
       <KeyBinding Command="{Binding EnterCommand}" Key="Enter" />
       <KeyBinding Command="{Binding DownSelectionCommand}" Key="Down" />
  </TextBox.InputBindings>
  <i:Interaction.Triggers>
        <i:EventTrigger EventName="KeyUp">
            <i:InvokeCommandAction  Command="{Binding CompleteCommand}" />
        </i:EventTrigger>
   </i:Interaction.Triggers>
</TextBox> 

然后确保命令的execute方法具有参数的正确事件args类型,然后在调用CompleteCommand时,您应该将事件args作为参数,并且您应该能够在视图模型上检查InputText属性以获取文字价值。

请注意,我在TextBox Text属性的绑定中添加了“UpdateSourceTrigger = PropertyChanged”。这将导致每次用户键入时在视图模型中更新属性。

有关InvokeCommandAction的默认行为,请参阅以下链接:

https://github.com/Microsoft/XamlBehaviors/issues/126

© www.soinside.com 2019 - 2024. All rights reserved.