Reputation: 61
I have textbox in my WPF application, i have binded one commandproperty with it , after inserting value once i press enter key , it's value gets added in ObservableCollection object. i have used TextBox input binding below is the code:
<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>
Here is the viewmodel's property
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));
}
Here i want textbox to be cleared once i add data in collection. i even tried with KeyDown event handler in code behind like below but it didn't get clear.
private void txtBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return)
{
txtBox1.Text = "";
}
}
Any help much appreciated.
Upvotes: 1
Views: 2809
Reputation:
You're going about it oddly...
First, bind a property of the ViewModel to the TextBox
<TextBox Text="{Binding TheTextBoxValue}" />
and (INotifyPropertyChanged implementation details omitted)
public string TheTextBoxValue
{
get { return _ttbv; }
set { _ttbv = vaule; NotifyOnPropertyChangedImplementationLol(); }
}
Now, you can use TheTextBoxValue and clear it out from your 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;
}
Upvotes: 2