2015-09-18 43 views
1

我在我的WPF应用程序中有文本框,我用它绑定了一个commandproperty,插入值后,我按下Enter键,它的值被添加到ObservableCollection对象中。我用下面文本框输入绑定代码:WPF:在输入按键后清除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> 

这里是视图模型的财产

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 = ""; 
     } 
    } 

任何帮助非常感谢。

回答

1

你绕了奇怪...

首先,视图模型的属性绑定到TextBox

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

和(INotifyPropertyChanged的实施细节省略)

public string TheTextBoxValue 
{ 
    get { return _ttbv; } 
    set { _ttbv = vaule; NotifyOnPropertyChangedImplementationLol(); } 
} 

现在,您可以使用TheTextBoxValue并将其从虚拟机中清除出去

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; 
} 
+0

是啊...它的工作,感谢您的评论:)。 –

+0

@PraveenDeewan这是一个答案,而不是评论。您还可以通过投票计数点击复选标记,告诉其他人这是一个正确的答案,它可以帮助您解决问题。这通常是在这里完成的事情:) – Will