为什么此事件处理程序多次抛出异常?

时间:2015-05-19 08:52:01

标签: c# wpf

我有一个用于IP地址输入的XamMaskedInput。看起来像: enter image description here

背后的代码:

using System;
using System.Diagnostics;
using System.Windows.Controls;
using System.Windows.Input;
using Infragistics.Controls.Editors;
using System.Net;

namespace Customizing.Views
{
    /// <summary>
    ///     Interaction logic for IpRangeFields.xaml
    /// </summary>
    public partial class IpRangeFields : UserControl
    {
        public IpRangeFields()
        {
            InitializeComponent();
        }

        private void Start_OnLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            var input = (XamMaskedInput) sender;
            try
            {
                var ip = input.Text.Replace("-", ".");
                var address = IPAddress.Parse(ip);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                Dispatcher.BeginInvoke((Action)(() => input.Focus()));
                e.Handled = true;
            }

        }
    }
}

当用户输入错误的IP地址时,它将抛出System.FormatException。问题是,它多次抛出异常,我的wpf应用程序frizzed。我怎么解决这个问题?

异常发生后,不应该离开输入框。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:4)

您正在注册经常发生的事件,并且您正在使用IPAddress.Parse,如果它无法解析IP地址,则会引发该事件。

相反,请使用TryParse

检查IP地址的有效性
var ip = input.Text.Replace("-", ".");
IPAddress ipAddress;
if (!IPAddress.TryParse(ip, out ipAddress))
{
    // The address is invalid.
}

另一个建议是使用内置验证机制的WPF来验证您的IP。有关如何执行此操作的详情,请参阅this

相关问题