2

Here's my code snippet :

<TextBox Text="{Binding Path=Amount, Mode=TwoWay, StringFormat=\{0:N\}}" />

If the user enters letters or a large number etc, the stringformat dies silently. How can i raise an exception instead ?

Thanks

AnthonyWJones
  • 187,081
  • 35
  • 232
  • 306
Maxime ARNSTAMM
  • 5,274
  • 10
  • 53
  • 76

2 Answers2

3

Bindings swallow exceptions thrown when text input cannot be converted to the data type required by the property on source object. However you can specify ValidatesOnException in the binding. That will cause the standard red border reporting of a conversion problem. BTW this is unrelated to the string format property which is only relevant for displaying the current value, it isn't in play when user is entering data.

    <TextBox Text="{Binding Path=Amount, Mode=TwoWay, StringFormat=\{0:N\}, ValidatesOnExceptions=True}" HorizontalAlignment="Left" Width="200"/>

Note I've limited the width and aligned to left. One of the problems with the default validation popup is that is that it is always displayed to the right, which is a bit of a problem when the text box right border is flush with the right edge of the silverlight control's right edge.

AnthonyWJones
  • 187,081
  • 35
  • 232
  • 306
2

Have you thought of writing a filter behavior that allows you to control exactly what goes into the text box?

Myles J
  • 2,839
  • 3
  • 25
  • 41
  • In WPF/Silverlight you can write reusable bahaviors for control types. For your scenario you could write a Textbox behaviour that limits the type of text entered e.g. numerics only. Have a read of these for some ideas: http://www.dataartist.net/blog/post/Silverlight-Behavior-Modifications-13-NumericOnlyBehavior.aspx http://csharperimage.jeremylikness.com/2009/10/silverlight-behaviors-and-triggers_07.html – Myles J Sep 12 '11 at 14:04
  • i was hoping to avoid adding attributes to my gazillion fields :/ But thanks, it will work if there's nothing else. – Maxime ARNSTAMM Sep 12 '11 at 14:11
  • or you could let Silverlights own validation system handle it. – AnthonyWJones Sep 12 '11 at 19:55