I am creating a WPF application where one of the field is UnitCost which is a property in a class. I have implemented INotifyPropertyChanged on the class which holds this property. I have a validation logic which throws an exception when the UnitCost is less than 0. I also have made use of ValidatesOnExceptions and NotifyOnValidationError attributes both set to true. Now when I change the textbox which is internally bind to UnitCost property from UI and input negative values a red adorner is displayed. However I have a flow in my application which changes the UnitCost from code behind. In this case I am not seeing any red adorner and my application crashes. I am not able to get why the application behaves in different ways when I directly change the UnitCost from UI and when I change it from code behind. Sample code:
public class Product : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private decimal unitCost;
public decimal UnitCost
{
get { return unitCost; }
set
{
if (value < 0)
{
throw new ArgumentException("Unitcost cannot be negative");
}
unitCost = value;
OnPropertyChanged("UnitCost");
}
}
}
In wpf window
<TextBox x:Name="txtUnitCost" Margin="5" Grid.Row="2" Grid.Column="1" Text="{Binding UnitCost, ValidatesOnExceptions=True, NotifyOnValidationError=True}">
</TextBox>
Now when I change the Unit cost from the textbox beside the Change Unit code button application crashes. Code behind is:
private void ChangeUnitCostHandler(object sender, RoutedEventArgs e)
{
var product = (Database.Product)gridProductDetails.DataContext;
decimal cost;
decimal.TryParse(txtUnitCostChange.Text, out cost);
product.UnitCost = cost;
}
While debugging it goes till throw statement, throws exception and application crashes. I am not able to find the reason why it behaves differently even if same UnitCost property is change once from UI directly from the Unit Cost text box and once from code behind.