c# - WPF : Clear TextBox text after enter key press

标签 c# wpf mvvm

我的 WPF 应用程序中有文本框,我已经绑定(bind)了一个命令属性,在我按下回车键插入值后,它的值被添加到 ObservableCollection 对象中。我使用了 TextBox 输入绑定(bind)下面是代码:

<TextBox x:Name="txtBox1" Grid.Row="0" Grid.Column="0" HorizontalAlignment="Left" Height="23" Margin="15,50,0,0" TextWrapping="Wrap"  VerticalAlignment="Top" Width="89" >
        <TextBox.InputBindings>
            <KeyBinding Command="{Binding Path=InsertCommand1}" CommandParameter="{Binding Path=Text, ElementName=txtBox1}" Key="Enter" />
        </TextBox.InputBindings>
</TextBox>

这是 View 模型的属性
private ICommand _insertCommand1;
    public ICommand InsertCommand1
    {
        get
        {
            if (_insertCommand1 == null)
                _insertCommand1 = new RelayCommand(param => AddItem1((String)param));
            return _insertCommand1;
        }
    }

    private void AddItem1(string res)
    {
        this.CollectionList.Add(Int32.Parse(res));
    }

在这里,我希望在集合中添加数据后清除文本框。我什至尝试在下面的代码中使用 KeyDown 事件处理程序,但并不清楚。
    private void txtBox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Return)
        {
            txtBox1.Text = "";
        }
    }

非常感谢任何帮助。

最佳答案

你这样做很奇怪...

首先,将 ViewModel 的一个属性绑定(bind)到 TextBox

<TextBox Text="{Binding TheTextBoxValue}" />

和(省略了 INotifyPropertyChanged 的​​实现细节)
public string TheTextBoxValue 
{ 
    get { return _ttbv; }
    set { _ttbv = vaule; NotifyOnPropertyChangedImplementationLol(); }
}

现在,您可以使用 TheTextBoxValue 并将其从 VM 中清除
private void AddItem1(string res)
{
    // Who needs validation? LIVE ON THE EDGE!
    this.CollectionList.Add(Int32.Parse(TheTextBoxValue));
    // or, if you use validation, after you successfully parse the value...
    TheTextBoxValue = null;
}

关于c# - WPF : Clear TextBox text after enter key press,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32660075/

相关文章:

android - 未设置 LiveData,永远不会调用观察者

c# - 什么时候用激活器,什么时候用工厂方法?

c# - .Net Core 2.0 Windows 服务

wpf - 在WPF Datagrid中处理多个选定的行

wpf - 触摸界面中的 Slider\ScrollViewer 无法正常工作

c# - MVVM 从 View 读取数据到模型

用作菜单的 WPF TreeView (MVVM 样式)

c# - WPF 复合窗口和 ViewModel

C# 使类静态化?

c# - Asp.Net Core 2.0 ArgumentNullException : Value cannot be null. 参数名称:connectionString