【问题标题】:How to pass textbox KeyEventArgs and textbox value in command wpf如何在命令 wpf 中传递文本框 KeyEventArgs 和文本框值
【发布时间】:2019-04-07 10:54:31
【问题描述】:

我正在为我有一个文本框之类的东西而苦苦挣扎

<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”事件。现在我正在为自动完成文本框工作,所以我提出了在工作正常的列表框中输入的建议。所以我需要绑定向下键以与此文本框绑定,以便在显示建议后用户可以按下向下键并从那里选择他想要的选项。 它可以很好地用于向下键的键绑定。

问题在于事件 keyup,因为在文本框内按下任何键都会触发此事件。现在我将文本框值作为命令参数发送,但我还需要使用 comamnd 参数发送 keyeventargs,这样我就可以找出按下了哪个键,当出现下键时我不会进一步执行该方法。

那么我如何将文本框值和 keyeventargs 作为命令参数传递,我严格遵循 mvvm 模式。

【问题讨论】:

  • 是否需要将TextBox 值作为命令参数传递?您不是已经在您的视图模型中将它作为InputText 了吗?

标签: wpf mvvm prism keyboard-events


【解决方案1】:

默认情况下,如果您未指定命令参数,则 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> 

然后确保您的命令的执行方法具有正确的参数事件参数类型,然后当调用 CompleteCommand 时,您应该将事件参数作为参数,并且您应该能够检查您视图上的 InputText 属性文本值的模型。

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

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

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

【讨论】:

    猜你喜欢
    • 2018-11-13
    • 2020-12-07
    • 1970-01-01
    • 1970-01-01
    • 2013-10-01
    • 2010-11-04
    • 2021-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多