在我的WPF视图中,我试图将事件绑定到Enter键,如下所示:
<TextBox Width="240" VerticalAlignment="Center" Margin="2" Text="{Binding SearchCriteria, Mode=OneWayToSource}">
<TextBox.InputBindings>
<KeyBinding Key="Enter" Command="{Binding EnterKeyCommand}"/>
<KeyBinding Key="Tab" Command="{Binding TabKeyCommand}"/>
</TextBox.InputBindings>
</TextBox>
Run Code Online (Sandbox Code Playgroud)
此代码有效,当用户按下Enter键时,我的EnterKeyCommand将触发.但问题是,当事件触发时,WPF尚未将文本框中的文本绑定到"SearchCriteria".因此,当我的事件触发时,"SearchCriteria"的内容为空.我可以在此代码中进行简单的更改,以便在我的EnterKey命令触发时可以获取文本框的内容吗?
小智 13
您可以通过将TextBox的InputBindings属性作为a CommandParameter传递给Command:
<TextBox x:Name="MyTextBox">
<TextBox.InputBindings>
<KeyBinding Key="Return"
Command="{Binding MyCommand}"
CommandParameter="{Binding ElementName=MyTextBox, Path=Text}"/>
</TextBox.InputBindings>
</TextBox>
Run Code Online (Sandbox Code Playgroud)
您也可以在后面的代码中执行此操作.
在检查输入/返回时,只需调用您的事件处理程序代码.
我知道这已经有6年的历史了,但是没有一个答案使用XAML完整地给出了正确的答案,也没有任何代码隐藏。我还有很多工作要做。供参考,方法如下。首先是XAML
<TextBox Text="{Binding SearchText, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">
<TextBox.InputBindings>
<KeyBinding Key="Enter" Command="{Binding SearchEnterHit}"/>
<KeyBinding Key="Return" Command="{Binding SearchEnterHit}"/>
</TextBox.InputBindings>
</TextBox>
Run Code Online (Sandbox Code Playgroud)
基本上,方法是将每个键都在每次击键时都扔到绑定的SearchText上。因此,一旦按下回车键,该字符串将完全出现在SearchText中。因此,在SearchEnterHit命令中,可通过SearchText属性使用TextBox中的整个字符串。
如上所述,UpdateSourceTrigger = PropertyChanged是将每次击键刷新到SearchText属性的方法。KeyBindings捕获Enter键。
这实际上是最简单的方法,不需要任何代码,也不需要所有XAML。确保您经常刷新SearchText属性的键,但这通常不是问题。
| 归档时间: |
|
| 查看次数: |
78392 次 |
| 最近记录: |