I recently started playing around with MVVM, and I stumbled across a problem it seems many before me have encountered.
Essentially I had a property of type double in my model, which was linked to a string property in my ViewModel, implementing the INotifyPropertyChanged interface, which was bound to the Text property of a text box whereby the UpdateSourceTrigger is set to PropertyChanged, however the text box would not let me input decimal places or minus signs, nor could I set the text box to blank without the app crashing.
I searched thoroughly for a solution to this and found a lot of possible solutions that worked in some respects but left me with other problems. In the end I've used a combination of things to get around this:
I found this to be of use, and by placing:
public App()
{
System.Windows.FrameworkCompatibilityPreferences.KeepTextBoxDisplaySynchronizedWithTextProperty = false;
}
in App.xaml.cs I could now insert decimal places in my text box. however I still couldn't use a '-' nor set the text box to blank.
To get around this I did two things. In my XAML I added the following StringFormat to my data binding.
<TextBox Text="{Binding StringLinkedToDouble, UpdateSourceTrigger=PropertyChanged, StringFormat=-N2}"/>
The '-' before the 'N2' allowed me to input a minus sign but unless I typed the numeric value first and then entered the '-' at the beginning of the number the code threw an error. To get around this, and the fact that I couldn't set the text box to blank without running into an error, I did this in my ViewModel:
public StringLinkedToDouble
{
get { return _model.DoubleToBeLinked.ToString(); }
set
{
if ((value != "") && (value != "-"))
_model.DoubleToBeLinked = Convert.ToDouble(value);
RaisePropertyChanged("StringLinkedToDouble");
}
}
While this may work, I am new to MVVM and the reason I am posting this is because this solution seemed very simple, almost too simple and I'm worried that this may not be 'good' as far as MVVM goes? I'm half expecting to be told that it isn't in fairness ha! And if that is the case then could someone suggest a better alternative? Thanks in advance! Also if there's anything else I've done which isn't proper MVVM then please let me know :)