通过吞下异常将WPF文本框限制为整数

时间:2012-08-14 03:25:21

标签: c# wpf

我编写了以下内容来限制WPF文​​本框只接受整数,并且只接受小于或等于35的数字:

在我的WindowLoaded事件中,我为'OnPaste'创建了一个处理程序:

DataObject.AddPastingHandler(textBoxWorkflowCount, OnPaste);

OnPaste包含以下内容:

private void OnPaste(object sender, DataObjectPastingEventArgs e)
{
    if (!IsNumeric(e.Source.ToString(), NumberStyles.Integer)) e.Handled = true;
}

我们强制数字的功能如下:

public bool IsNumeric(string val, NumberStyles numberStyle)
{
    double result;
    return double.TryParse(val, numberStyle, CultureInfo.CurrentCulture, out result);
}

具有错误的特定文本框也应限制为数字<= 35。为此,我添加了以下TextChanged事件:

private void TextBoxWorkflowCountTextChanged(object sender, TextChangedEventArgs e)
        {
            try
            {
                if (textBoxWorkflowCount == null || textBoxWorkflowCount.Text == string.Empty || Convert.ToInt32(textBoxWorkflowCount.Text) <= 35) return;
                MessageBox.Show("Number of workflow errors on one submission cannot be greater then 35.", "Workflow Count too high", MessageBoxButton.OK, MessageBoxImage.Warning);
                textBoxWorkflowCount.Text = "";
            }
            catch(Exception)
            {
                // todo: Oh the horror! SPAGHETTI! Must fix. Temporarily here to stop 'pasting of varchar' bug
                if (textBoxWorkflowCount != null) textBoxWorkflowCount.Text = "";
            }

        }

虽然这可以完成这项任务并且工作起来非常讨厌/讨厌但我很想知道为了改善自己可以做得更好......特别是如此,不必吞下一个例外。

2 个答案:

答案 0 :(得分:1)

这对你有用吗?将TextBoxWorkflowCountTextChanged的内容替换为:

if (textBoxWorkflowCount == null || textBoxWorkflowCount.Text == string.Empty) return;
int workflowcount = 36;
if (int.TryParse(textBoxWorkflowCount.Text, out workflowcount) && workflowcount > 35) {
    MessageBox.Show("Number of workflow errors on one submission cannot be greater then 35.", "Workflow Count too high", MessageBoxButton.OK, MessageBoxImage.Warning);
    textBoxWorkflowCount.Text = "";
}
else if (workflowcount == 36) {
    textBoxWorkflowCount.Text = "";
}

答案 1 :(得分:1)

基于QtotheC的回答,我在经过多次重构后得到了以下内容。在此为未来的访问者添加:)

    private void TextBoxWorkflowCountTextChanged(object sender, TextChangedEventArgs e)
    {
        if (string.IsNullOrEmpty(textBoxWorkflowCount.Text))
            return;

        int workflowCount;

        if (!int.TryParse(textBoxWorkflowCount.Text, out workflowCount) || workflowCount <= 35) return;
        MessageBox.Show("Number of workflow errors on one submission cannot be greater then 35.", "Workflow Count too high",
                        MessageBoxButton.OK, MessageBoxImage.Warning);
        textBoxWorkflowCount.Text = "35";
    }