I am tring to get the new value that a user set in a cell of a datagrid. The datagrid binds to a collection of the view model.
The type of the property that is binded in the cell is a decimal, that I would like to can set decimal values.
To get the value the new value, I use this code:
<DataGridTextColumn Header="Cantidad" Binding="{Binding Cantidad, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" IsReadOnly="false"/>
<i:Interaction.Triggers>
<i:EventTrigger EventName="CellEditEnding">
<i:InvokeCommandAction Command="{Binding CeldaFinalizandoEdicionCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
View model:
private RelayCommand _celdaFinalizandoEdicionCommand;
public RelayCommand CeldaFinalizandoEdicionCommand
{
get { return _celdaFinalizandoEdicionCommand ?? (_celdaFinalizandoEdicionCommand = new RelayCommand(async param => await OnCeldaFinalizandoEdicion(), param => true)); }
}
private async Task OnCeldaFinalizandoEdicion()
{
try
{
decimal myNewValue = SelectedItem.Cantidad;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
The idea it is to handle the event CellEditEnding, so I could handle the cell edited. I need to set the binding mode of the cell to PropertyChanged, because if not, in the view model method I still get the old value.
I need to set the binding to two way, because if not, I would get a blank cell after editing.
However, this has a problem. To can write a decimal, I have to write the number without decimal point and then go to dot position and write it. If I write the dot decimal when there is not another number after it, it considerates it is a int value, because of validation. So it is hard to write a decimal value.
How could I could I write a decimal in a easy way when the binding property is a decimal?
Thanks.
This has always worked for me. I hope I'm understanding your question right. Use the StringFormat in your Binding on the Column
Binding="{Binding Amount, StringFormat=N2}"