Search code examples
c#wpfdata-bindingdatagrid

WPF DataGrid - DataGridTextColumn decimal/double/float input with PropertyChanged


I'm having trouble with decimal (double/float) inputs in DataGridTextColumn with UpdateSourceTrigger=PropertyChanged.

(1) I have searched several sites and many suggest to change this to LostFocus. Im not very keen on this implementation cause the behaviour with PropertyChanged is what I require. Unless there is a way to get the same result with LostFocus??

I have read the following articles on stackoverflow - Link 1, Link 2, Link 3, Link 4, Link 5 & Link 6

(2) Using Binding="{Binding StringFormat=N2}"or its variation has a very annoying behavior as described in the comments in Link 4.

(3) The other method is to allow string input and parse it as double in the back end. This is fine-ish, and I'm holding onto it as a last resort solution only.

(4) Lastly in the same Link 4, a solution mentioned by xmedeko - System.Windows.FrameworkCompatibilityPreferences.KeepTextBoxDisplaySynchronizedWithTextProperty = false; for .NET 4.5 or later only.

I do have the newer version but not sure how/where to implement this line of code. Or if there's a way to turn this property false in the XAML itself? Any help is greatly appreciated. Unable to reply as a comment on that link due to my reputation level.

If there is a any other neater way while keeping the behavior similar to PropertyChanged, would be very helpful.

CODE
XAML - <DataGridTextColumn Header="Rate" Binding="{Binding Path=Rate, UpdateSourceTrigger=PropertyChanged}" Width="90"/>

cs -

public void NotifyPropertyChanged(string property)
{
   PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
}

public double Rate
{
   get { return rate; }
   set { rate = value; NotifyPropertyChanged("Rate"); }
}

The code is actually very simple. This is displayed on a datagrid. The DataGridTextColumn does not accept decimal values and this correctly noted by Chevul Ervin in Link 2 -

UpdateSourceTrigger=PropertyChanged reevalutes the text on every keystroke. A number that ends in a decimal point is invalid. Change the UpdateSourceTrigger to LostFocus (same as removing it) or try to type the '.' while you have other digits after it.


Solution

  • I did quite a bit of research and found no solution. So going with Option 3 - allow string input and handle it in the backend.