Reputation: 36050
I have the following binding in my wpf application
xaml:
<TextBox Text="{Binding Amount, StringFormat=c}" Name="txtAmount" />
c# (code behind):
public partial class MainWindow : Window, INotifyPropertyChanged
{
public MainWindow()
{
InitializeComponent();
// needed to create the binding
this.DataContext = this;
}
private decimal _Amount;
public decimal Amount
{
get {
return _Amount;
}
set{
_Amount= value;
OnPropertyChanged("Amount");
}
}
public event PropertyChangedEventHandler PropertyChanged = delegate { };
private void OnPropertyChanged(string propertyName)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
//.....
that code works fine. The property Amount in my code behind will be updated whenever I change the value of txtAmount and also the other way around (changing the value of Amount in C# will update txtAmount)
Anyways how can I update amount every time I change the text in the control txtAmount? I don't want to wait until txtAmount loses focus so that Amount get's updated in the code behind.
Things I have tried:
txtAmount.TextChanged += (a, b) =>
{
Amount = decimal.Parse(txtAmount.Text);
};
Recall that my txtAmount is formatted as currency therefore if it has the value of 1 the txtAmount will display $1.00 I know that I should be able to replace the $ for nothing in order to be able to cast it to decimal. If this application where to use a different culture say for instance es for Spanish then the textbox will display a eruo instead of the $ and I will have to replace that symbol in order to be able to cast it.
So in short is there a way of being able to update the Amount property that is binded to my txtAmount control everytime the text changes in that control instead of when the control looses focus?
Upvotes: 3
Views: 561
Reputation: 1575
Set the binding property UpdateSourceTrigger
to PropertyChanged
<TextBox Text="{Binding Amount, StringFormat=c, UpdateSourceTrigger=PropertyChanged}" Name="txtAmount" />
Upvotes: 8
Reputation: 172390
So in short is there a way of being able to update the Amount property that is binded to my txtAmount control everytime the text changes in that control instead of when the control looses focus?
In short:
<TextBox Text="{Binding Amount, StringFormat=c,
UpdateSourceTrigger=PropertyChanged}" Name="txtAmount" />
Upvotes: 3