2

我编写了以下内容来限制 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 = "";
            }

        }

虽然这可以完成工作并且工作它非常讨厌/骇人听闻,我很想知道如何为了提高自己而做得更好......尤其是不必吞下例外。

4

2 回答 2

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 = "";
}
于 2012-08-14T03:54:12.743 回答
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";
    }
于 2012-08-14T04:07:26.120 回答