Skip to main content
 首页 » 编程设计

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

2024年02月06日18powertoolsteam

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

以及背后的代码:

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有关如何执行此操作的更多信息。