【问题标题】:WPF CommandParameter in Textbox文本框中的 WPF 命令参数
【发布时间】:2010-11-04 06:01:41
【问题描述】:

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

我尝试使用命令参数,但它不适合我。

请帮忙..

谢谢 沙拉特

【问题讨论】:

    标签: wpf mvvm textbox command


    【解决方案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());
    }
    

    【讨论】:

    • 我想使用文本框 textchanged 或当用户从键盘单击输入文本框时。不想按按钮。
    • 如果您使用的是命令,那么您必须像按钮一样使用 ICommandSource。命令与事件处理程序不同。
    【解决方案2】:

    如果我希望在用户按下回车时执行命令,我喜欢使用它。注意 IsDefault 绑定的巧妙使用 :-)

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

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

    【讨论】:

    • 非常感谢..如果按钮折叠它不会执行。我将宽度设置为 0 :-)
    • 我可以对列表框做同样的事情吗?我的意思是当我双击列表框项目时。按钮点击甚至应该被提升。
    • 我不知道。为此,我在代码隐藏中手动调用了该命令。不过,我对 xaml 还是很陌生,所以谁知道呢。
    • 我认为将按钮的可见性设置为隐藏(而不是折叠)就可以了。
    • @Botz3000 你才是真正的MVP
    【解决方案3】:

    此代码适用于我

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

    【讨论】:

      猜你喜欢
      • 2018-11-13
      • 1970-01-01
      • 2013-10-01
      • 2010-09-14
      • 2020-11-26
      • 2012-03-10
      • 2011-03-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多