繁体   English   中英

WPF:输入键后清除TextBox文本

[英]WPF : Clear TextBox text after enter key press

我的WPF应用程序中有文本框,我已将其绑定到一个命令属性,一旦按Enter键插入值后,它的值就会添加到ObservableCollection对象中。 我已经使用了TextBox输入绑定,下面是代码:

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

这是viewmodel的属性

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的属性绑定到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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM