WPF How to create a Custom Textbox with validation and binding

前端 未结 4 1103
死守一世寂寞
死守一世寂寞 2021-01-15 05:47

I\'m developing a custom text box for currency editing.
I\'ve seen some ready to use ones, but they\'re complicated and/or not really usable, forcing you to bad practi

4条回答
  •  自闭症患者
    2021-01-15 06:04

    I don't think this is actually possible, except for the simple case of a box that only allows digits. Ideally you'd like a box that can only contain a valid entry, but decimals contain some characters (like '-' and '.') that are not valid on their own. The user can't start by typing a '-' without putting the box into an invalid state.

    Similarly they could enter '1.', and then delete the 1 and leave the box in an indeterminate state. Sure, it causes a validation error and a red border, but your view model still thinks the value is 1, and isn't aware of the problem.

    For positive integers, you can only allow digits and automatically insert a zero when blank (although that's a little unfriendly)

    For decimals and negative integers, I think the best you can do is to constrain the keys a user can type, but you still need to wrap your number property in a string and validate it - either when the OK button is pressed, or ideally implement INotifyDataError to display the error and disable the OK button.

提交回复
热议问题