簡體   English   中英

C# WPF - 輸入驗證 - 不能在文本框中使用小數點(句點)

[英]C# WPF - Input Validation - Can't use decimal points (periods) in TextBoxes

我使用 IDataErrorInfo 進行了輸入驗證,但它阻止我在 TextBox 中使用小數點(句點)。 例如,嘗試輸入1.222是行不通的。 它只是停在 1 並且不注冊. 按鍵——也沒有調試 output。 它還在嘗試接受我的輸入(這會引發異常),即使驗證表明它是錯誤的格式。 我怎樣才能解決這個問題?

主窗口.xaml

<TextBox Text="{Binding Density, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" Name="tb_density" Grid.Column="2" HorizontalAlignment="Left" Height="20" Margin="0,4,0,0" Grid.Row="8" TextWrapping="Wrap" VerticalAlignment="Top" Width="140"/>

主窗口.xaml.cs

private MyViewModel m_ViewModel;
m_ViewModel = new MyViewModel();
DataContext = m_ViewModel;

private void Run_Click(object sender, RoutedEventArgs e) {

    Console.WriteLine("Density: " + (1 * Convert.ToDouble(tb_density.Text))).ToString();
}

MyViewModel.cs

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace foobar{

    class MyViewModel : INotifyPropertyChanged, IDataErrorInfo {

        private double m_density;

        public MyViewModel () {

        }

        public double Density {

            get {

                return m_density;
            }
            set {

                if (m_density!= value) {

                    m_density= value;
                    OnPropertyChanged("Density");
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string propertyName) {

            if (PropertyChanged != null) {

                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public string Error {

            get { return "...."; }
        }

        /// <summary>
        /// Will be called for each and every property when ever its value is changed
        /// </summary>
        /// <param name="columnName">Name of the property whose value is changed</param>
        /// <returns></returns>
        public string this[string columnName] {

            get {

                return Validate(columnName);
            }
        }

        private string Validate(string propertyName) {

            // Return error message if there is error on else return empty or null string
            string validationMessage = string.Empty;

            switch (propertyName) {

                case "Density":
                    if(!double.TryParse(Density.ToString(), out _)) {

                        validationMessage = "Error";
                    }
                    break;
            }

            return validationMessage;
        }
    }
}

您可以嘗試如下所示的內容:

private double _density;
public string Density{
 get => _density.ToString();
 set 
 {
   if(double.TryParse(value, out var density){
     _density = density;
   }
 }

順便提一句。 當您將點添加到一個“1”時,您的代碼可能無法正常工作,因為if (m_density!= value) 仍然等於“1”,因此該值不會更新。

我認為您的問題浮出水面,因為您將 UpdateSourceTrigger 設置為 PropertyChanged。 這意味着每次您在鍵盤上鍵入內容時,都會觸發錯誤驗證。 因此,如果您鍵入“1”,則當前沒有錯誤。 但是如果你接下來輸入“.”,你現在有一個包含“1”的文本框。 這將無法通過驗證,因為它不是一個實數。 如果您更改 UpdateSourceTrigger=LostFocus,那么它只會在您離開文本框后評估錯誤驗證。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM