I'm working on an application that does some custom financial data importing, and the user needs to be able to make small changes to numbers to make transactions balance. (sometimes rounding errors in one system or another cause imbalances and they need to be manually adjusted). The errors are between two systems that I have no ability to control, and the nature of the changes requires a human to decide what change to make.
I've gotten data binding to work, except that there is a huge annoyance when entering data. If the user wants to enter a very small negative number, the input keeps overriding their typing to remove negative signs and decimal places.
For example: If I try to type '-0.06' without stopping, I end up with just '6'. If I stop before I get to the 6. If I've typed '-0.0' and realize something is messed up, all there is is a '0'. It's possible to enter the desired value, but I need to make a series of edits like '1006','10.06','0.06','-0.06'. This is not very productive, and difficult to teach someone to do.
The XAML for my templatecolumn is as follows:
<DataGridTemplateColumn Header="Amount">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=LineAmount, Mode=OneWay, StringFormat=C2}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<TextBox Text="{Binding Path=LineAmount, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
Any suggestions? I've tried making a custom IValueConverter
implementation, but still had the same issue.
I think binding straight to a double is what is giving you the problem. Thinking, when you first type in "-" that cannot be converted to a double, so the string format cannot be applied, breaking it. You might be able to see this in the Output
window in Visual Studio during runtime. Instead, create a backing property that'll convert from string to double, then update the double amount.
<DataGridTemplateColumn Header="Amount">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=LineAmount, Mode=OneWay, StringFormat=C2}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<TextBox Text="{Binding Path=LineAmountStr, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
Your view model class:
public class TheViewModel
{
private string _lineAmountStr;
public string LineAmountStr
{
get { return _lineAmountStr; }
set
{
double amt;
if(double.TryParse(value, out amt))
{
LineAmount = amt;
}
_lineAmountStr = value;
NotifyPropertyChanged("LineAmountStr");
}
private double _lineAmount;
public double LineAmount
{
get { return _lineAmount; }
set
{
_lineAmount = value;
NotifyPropertyChanged("LineAmount");
}
}
}