简体   繁体   中英

Restrict user input to positive integers in wpf datagrid

I have a datagrid in which i have quantity field which is off type integer. Now i want to restrict my user to enter only positive integers. I dont want a solution of handling inputs on datagrid key events. Any suggestions?

And Here is the convertor i am using

public class ValueConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        { return value; }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (!OnlyPositiveIntergerAllowed(value.ToString()))
            {
                string s = Regex.Replace(value.ToString(), @"[^0-9]+", string.Empty);

                if(s=="")
                return 0;
                else
                    return s;

            }
           if (value is string && (string)value == "")
            {
                return 0;
            }

            return value;

        }
        private static bool OnlyPositiveIntergerAllowed(string text)
        {
            var regex = new Regex("[^0-9]+"); //regex that matches disallowed text
            return !regex.IsMatch(text);
        }
}

Note: Its working fine (ie if 123dasd. it converts on lost focus 123), but i allows user to input (dasd.).

You can use DataGridTemplateColumn and IntegerUpDown from the Extended WPF Toolkit for this situation.

Example:

            <DataGridTemplateColumn Header="Amount">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <toolkit:IntegerUpDown 
                                    Minimum="0"
                                    Value="{Binding Amount}"
                            />
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>

You can also use DecimalUpDown .

The solution you seek is called validation.

A search for WPF validation will provide plenty of links, here is one that looks pretty good: http://wpftutorial.net/DataValidation.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM