文本框中的 WPF 命令参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1016881/
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
WPF CommandParameter in Textbox
提问by Botz3000
I am using MVVM pattern and i have a textbox in parent window and want to send some text to the popup window which will appear on Textchanged.
我正在使用 MVVM 模式,并且我在父窗口中有一个文本框,并且想要将一些文本发送到将出现在 Textchanged 上的弹出窗口。
I tried using commandparameter but it is not working for me.
我尝试使用 commandparameter 但它对我不起作用。
Please help..
请帮忙..
Thanks Sharath
谢谢莎拉
回答by Botz3000
If i want the command to be executed if the user presses enter, i like to use this. Note the clever use of the IsDefault Binding :-)
如果我希望在用户按下 Enter 时执行命令,我喜欢使用它。注意 IsDefault 绑定的巧妙使用 :-)
<TextBox x:Name="inputBox"/>
<Button Command="{Binding CutCommand}"
CommandParameter="{Binding Text, ElementName=inputBox}"
Content="Cut"
IsDefault="{Binding IsFocused, ElementName=inputBox}" />
If you don't want the button to be visible, you can set its visibility to collapsed of course. I think it'll still execute the command if you hit enter.
如果您不希望按钮可见,当然可以将其可见性设置为折叠。我认为如果你按回车,它仍然会执行命令。
回答by Alexandre Beaulac
This code works for me
这段代码对我有用
<UserControl x:Class="Test"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
Height="Auto" Width="Auto">
<UserControl.InputBindings>
<KeyBinding Key="Enter" Command="{Binding ScanCommand}" CommandParameter="{Binding Text, ElementName=tbBarcode}"/>
</UserControl.InputBindings>
<Grid Name="LayoutRoot">
<TextBox x:Name="tbBarcode" Height="23"/>
</Grid>
</UserControl>
回答by Matt Hamilton
What have you tried? This code works for me:
你尝试过什么?这段代码对我有用:
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Window.CommandBindings>
<CommandBinding Command="Cut" Executed="CommandBinding_Executed" />
</Window.CommandBindings>
<StackPanel>
<TextBox x:Name="textBox1" />
<Button Command="Cut"
CommandParameter="{Binding Text,ElementName=textBox1}"
Content="Cut" />
</StackPanel>
</Window>
With this event handler:
使用此事件处理程序:
private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
MessageBox.Show(e.Parameter.ToString());
}