WPF,MVVM中TextBox,限制輸入數字,保留2位小數點,輸入超出設定值時,提示

開始是直接綁定interactivity

 <i:Interaction.Triggers>
    <i:EventTrigger EventName="TextChanged">
       <i:InvokeCommandAction Command="{Binding D_TextChanged_Command}" CommandParameter="{Binding D_RMS}"/>
     </i:EventTrigger>
</i:Interaction.Triggers>

由於我的TEXT 也綁定到後臺的,這樣是ViewModels更新不是實時的,在get set裏也不是直接能判斷的。

 /// <summary>
        /// RMS距離D
        /// </summary>
        public float D
        {
            get{ return sk.D; }
            set
            {
                sk.D = value;

          
                this.OnPropertyChanged("D");
            }
        }
  <TextBox Name="D_RMS"   PreviewTextInput="D_RMS_PreviewTextInput"  HorizontalAlignment="Left" Height="36" Margin="750.667,540,0,0" TextWrapping="Wrap" Text="{Binding D, Mode=TwoWay}"  VerticalAlignment="Top" Width="164" Grid.Column="1" >

 

後面直接在.xaml.cs裏是

先是

限制輸入數字

PreviewTextInput="D_RMS_PreviewTextInput"

      //限制輸入數字
        private void D_RMS_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            Regex re = new Regex("[^0-9]+");
            // Regex re = new Regex("[^0-9.-]+");//小數點和負號

            e.Handled = re.IsMatch(e.Text);
        }

 

超值提醒, TextChanged="D_RMS_TextChanged"  ,TXET改變事件

 //輸入錯誤時提醒
        private void D_RMS_TextChanged(object sender, TextChangedEventArgs e)
        {
            D_RMS.ScrollToEnd();
            string st = D_RMS.Text;
            string hint = fs.Text;
            if (st == "" || hint=="")
            {
                return;
            }
            int D_vlae = int.Parse(st);
            int fs_vlae = int.Parse(hint);

            int vlae = 40960 / fs_vlae;
            if (D_vlae > vlae)
            {
                if (co1.IsChecked == true)
                {
                    D_hint.Content = "只能輸入比" + vlae.ToString() + "小的整數";
                    D_hint. Foreground= new SolidColorBrush(Colors.Red);

                }
            }
            else 
            {
                D_hint.Foreground = new SolidColorBrush(Colors.Black);
                if (co1.IsChecked == true)
                {
                    D_hint.Content = "s/10";
                 }
                else {
                    D_hint.Content = "m";
                }
            }
            D_RMS.ScrollToEnd();

        }

 

 

本來還想在TextChanged寫小數點位數限定的,突然想起一個神奇的StringFormat='f2',直接在TEXT,中設置就好了,

 <TextBox   PreviewTextInput="TextBox_PreviewTextInput"  HorizontalAlignment="Left" Height="36" Margin="750.667,300,0,0" TextWrapping="Wrap" Text="{Binding TR0, Mode=TwoWay,StringFormat='f2'}" VerticalAlignment="Top" Width="164" Grid.Column="1"/>

 

效果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章