文本框中的WPF CommandParameter

时间:2009-06-19 08:17:53

标签: wpf mvvm textbox command

我正在使用MVVM模式,我在父窗口中有一个文本框,并希望将一些文本发送到弹出窗口,该窗口将显示在Textchanged上。

我尝试使用命令参数,但它对我不起作用。

请帮助..

由于 沙拉斯

3 个答案:

答案 0 :(得分:27)

如果我希望在用户按下回车的情况下执行该命令,我想使用它。注意聪明地使用IsDefault绑定: - )

<TextBox x:Name="inputBox"/>
<Button Command="{Binding CutCommand}" 
        CommandParameter="{Binding Text, ElementName=inputBox}" 
        Content="Cut" 
        IsDefault="{Binding IsFocused, ElementName=inputBox}" />

如果您不希望该按钮可见,则可以将其可见性设置为折叠。如果你点击回车,我认为它仍会执行命令。

答案 1 :(得分:2)

此代码适用于我

<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>

答案 2 :(得分:1)

你有什么尝试?这段代码适合我:

<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>

使用此事件处理程序:

private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
    MessageBox.Show(e.Parameter.ToString());
}
相关问题