2015-09-18 47 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