zoukankan      html  css  js  c++  java
  • WPF笔记: NumberStringTextbox 并带错误提示

    (转载请注明来源:cnblogs coder-fang)

    自定义number string textbox 在wpf中,可以在xaml层控制是否为空,长度限制等


    1.  创建textbox父类,使其具有相关依赖属性:

      

     public class TextboxBase:TextBox
        {
            
            public bool CanEmpty
            {
                get { return (bool)GetValue(CanEmptyProperty); }
                set
                {
                    SetValue(CanEmptyProperty, value);
                    ValidText();
                }
    
            }
    
            public int MaxTextLength
            {
                get { return (int)GetValue(MaxTextLengthProperty); }
                set
                {
    
                    SetValue(MaxTextLengthProperty, value);
                }
            }
            public bool Valid
            {
                get { return (bool)GetValue(ValidProperty); }
                set
                {
                    SetValue(ValidProperty, value);
                }
            }
            public string InvalidText
            {
                get { return (string)GetValue(InvalidTextProperty); }
                set
                {
                    SetValue(InvalidTextProperty, value);
    
                }
            }
            public static readonly DependencyProperty MaxTextLengthProperty =
               DependencyProperty.Register("MaxTextLength", typeof(int), typeof(TextboxBase));
            public static readonly DependencyProperty ValidProperty =
               DependencyProperty.Register("Valid", typeof(bool), typeof(TextboxBase));
            public static readonly DependencyProperty InvalidTextProperty =
               DependencyProperty.Register("InvalidText", typeof(string), typeof(TextboxBase));
            public static readonly DependencyProperty CanEmptyProperty =
              DependencyProperty.Register("CanEmpty", typeof(bool), typeof(TextboxBase));
            public delegate bool ValidDelegate(out string Invalidtext);
            public ValidDelegate ValidFunc;
    
            public TextboxBase()
            {
                this.TextChanged += TextboxBase_TextChanged;
                CanEmpty = false;
                MaxTextLength = Int32.MaxValue;
    
                ValidFunc = (out string invalidtext) =>
                {
                    invalidtext = "";
                    return true;
                };
            }
    
            private void TextboxBase_TextChanged(object sender, TextChangedEventArgs e)
            {
                ValidText();
            }
    
            public virtual bool ValidText()
            {
    
                if (!CanEmpty && Text == "" && DataContext != null)
                {
                    Valid = false;
                    InvalidText = "Can not be empty";
                    return false;
                }
                else if (Text.Length > MaxTextLength)
                {
                    Valid = false;
                    InvalidText = "Max length is " + MaxTextLength;
                    return false;
                }
                else
                {
                    InvalidText = null;
                    Valid = true;
                    return true;
                }
    
            }
        }

    2.  创建Number string类:

     public class NumStrTextbox:TextboxBase
        {
            Regex regex = new Regex(@"^d+$");
            public NumStrTextbox()
            {
                this.PreviewKeyDown += NumStrTextbox_PreviewKeyDown;
                System.Windows.Input.InputMethod.SetIsInputMethodEnabled(this, false);
            }
            public override bool ValidText()
            {
                var ret = base.ValidText();
                if (!ret)
                {
                    return false;
                }
                if (!regex.IsMatch(Text))
                {
                    InvalidText = "Only numbers is allowed";
                    Valid = false;
                    ret = false;
                }
                return false;
            }
    
            private void NumStrTextbox_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
            {
                if (((e.Key >= Key.D0 && e.Key <= Key.D9) ||(e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9))
                    &&!e.KeyboardDevice.IsKeyDown(Key.LeftShift)&& !e.KeyboardDevice.IsKeyDown(Key.LeftShift)
                   )
                {
                    
                }
                
                else if (e.Key == Key.Back || e.Key == Key.Delete || (e.Key >= Key.Left && e.Key <= Key.Down) ||
                    e.Key == Key.Tab || 
                    (e.Key >= Key.End && e.Key <= Key.Home))
                {
                }
                else
                {
                    e.Handled = true;
                    return;
                }
            }
        }

    3.  创建textbox相关style,使其在异常有红色提示信息

    <Style TargetType="UITextbox:TextboxBase" x:Key="WPFUITextboxBaseStyle" >
            <Setter Property="VerticalAlignment" Value="Center"></Setter>
            <Setter Property="VerticalContentAlignment" Value="Center"></Setter>
            <Setter Property="CaretBrush" Value="White"></Setter>
            <Setter Property="MinHeight" Value="25"></Setter>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type UITextbox:TextboxBase}">
                        <Grid>
                            <Grid.RowDefinitions>
                                <RowDefinition Height="auto" />
                                <RowDefinition/>
                            </Grid.RowDefinitions>
                            <TextBlock Grid.Row="0" Foreground="Salmon" Text="{TemplateBinding InvalidText}" Visibility="{TemplateBinding Valid,Converter={StaticResource TrueCollapseCvt}}"></TextBlock>
                            <Border Grid.Row="1"  x:Name="Bd" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="true">
                                <ScrollViewer x:Name="PART_ContentHost" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
                            </Border>
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
    
                <Trigger Property="Valid" Value="false">
                    <Setter Property="BorderBrush" Value="Red"></Setter>
                </Trigger>
    
            </Style.Triggers>
    
        </Style>

    效果图:

  • 相关阅读:
    OZ Report 오즈 리포트 개발
    日期 英文 英语 韩文 韩语
    行合并
    R内存扩展 win7内存扩展
    计算日期函数
    C#颜色 Color.FromArgb ColorTranslator 16进制
    Phone
    浏览器 UserAgent
    context.Request.Files post 上传问题件
    The connection to adb is down, and a severe error has occured.
  • 原文地址:https://www.cnblogs.com/coder-fang/p/11224066.html
Copyright © 2011-2022 走看看