WINUI 引入 CommunityToolkit.WinUI.UI进行数据验证

发布时间 2023-07-08 18:04:46作者: 盛沧海

 

先在xaml命名空间中引入   xmlns:ui="using:CommunityToolkit.WinUI.UI"

textbox中进行IP验证如下:

            <TextBox x:Name="textBox" Width="200" Height="30" Background="AliceBlue" 
                     ui:TextBoxExtensions.CustomMask="2:[0-2],5:[0-9]"
                     ui:TextBoxExtensions.Mask="255.255.255.255" TextChanged="textBox_TextChanged"
                     ui:TextBoxExtensions.MaskPlaceholder=" "
                    
                    />
CustomMask
设置自定义的掩码,
"2:[0-2],5:[0-9]"
2代表:为0~2的数值,闭区间;
5代表:为0~9的数值,闭区间,为什么不用9是由于这个拓展包中9被定义为了数字,具有特殊的意义。

按上述定义,所以Mask中就为
"255.255.255.255"


另由于上述限制后并不能保证IP地址的正确性,于是就在
TextChanged中添加了相应事件,再次进行验证。
 private void textBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            var textbox = (TextBox)sender;
            var txt = textbox.Text;
            var arr=txt.Split('.');
            if (int.TryParse(arr[0],out int a0))
            {
                if (a0==0)
                {
                    textbox.BorderBrush = new SolidColorBrush(Colors.Red);
                    return;
                }
            }

            foreach (var item in arr)
            {
                if (int.TryParse(item, out int val)){
                    if (val>255)
                    {
                        textbox.BorderBrush = new SolidColorBrush(Colors.Red);
                        return;
                    }
                }
            }
            textbox.ClearValue(TextBox.BorderBrushProperty);
        }

验证不合格,于是将文本框的边框设置为红色,以期起到警示作用。

 

参考链接:TextBoxExtensions - Windows Community Toolkit | Microsoft Learn