c# - 为什么这个事件处理程序多次抛出异常?

标签 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 应用程序崩溃。我怎么解决这个问题?

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

最佳答案

您正在注册一个经常发生的事件,并且您正在使用 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有关如何执行此操作的更多信息。

关于c# - 为什么这个事件处理程序多次抛出异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30320904/

相关文章:

c# - 为什么我的网站上的重定向会将我带到 azure.websites.net 而不是我的域?

c# - 如何将作为参数传递的 KeyValuePair 转换为 Command_Executed?

c# - 如何添加动态控件而不是静态控件?

c# - WPF INotifyPropertyChanged 是如何工作的?

c# - 设置 WPF TreeView 的样式

c# - 如何在linq中使用if else

c# - 从 Powershell 调用带有 Expression<Func> 参数的 C# 方法

c# - 如何让我的 C# 程序休眠 50 毫秒?

c# - 通过网络运行 .net 应用程序

c# - 在 Canvas 上分组项目