On按钮单击WPF中的验证

时间:2013-04-17 17:52:41

标签: wpf wpf-controls wpf-4.0

我正在研究WPF应用程序。在我的应用程序中,有不同的表单来保存数据。我希望在按钮点击或从控件丢失焦点时验证数据。我希望WPF验证像ASP.Net验证一样工作。

页面加载后我不知道表单验证。它应该仅在用户从控制中失去焦点或用户点击按钮时验证。

我在google上做了很多R& D.但我确实找到了安装解决方案的任何正确设置。

请帮帮我。

1 个答案:

答案 0 :(得分:-1)

在这个例子中,我向您展示了两个带有验证的文本框......

XAML编码......

    <TextBlock Text="Throw Exception in Property" Grid.Column="1" Grid.Row="0" VerticalAlignment="Center" FontSize="22" Foreground="Chocolate" />
    <TextBlock Text="Name " Grid.Column="0" Grid.Row="1" VerticalAlignment="Center" HorizontalAlignment="Center" FontSize="15" Foreground="DarkGreen" />
    <TextBlock Text="Age" Grid.Column="0" Grid.Row="2" VerticalAlignment="Center" HorizontalAlignment="Center" FontSize="15" Foreground="DarkGreen" />

    <TextBox Name="txtName" Grid.Row="1" Grid.Column="2" HorizontalAlignment="Left" Width="170" Height="30" Background="Azure" Text="{Binding Path=pName,Mode=TwoWay,ValidatesOnExceptions=True}"/>
    <TextBox Name="txtAge" Grid.Row="2" Grid.Column="2" HorizontalAlignment="Left" Width="170" Height="30" Background="Azure" Text="{Binding Path=pAge,Mode=TwoWay,ValidatesOnExceptions=True}"/>
    <Button Name="btnSubmit" Content="Submit" Grid.Row="4" Height="30" Click="btnSubmit_Click"/>

C#编码

    private void Page_Loaded(object sender, RoutedEventArgs e)
    {
        Student s = new Student();
        this.DataContext = s;
    }

    public class Student : INotifyPropertyChanged
    {
        string name;
        int age;

        public string pName
        {
            get 
            {
                return name;
            }

            set
            {
                if (string.IsNullOrWhiteSpace(value))
                {
                    throw new ArgumentException("Name field must be enterd.");
                }
                name = value;
                OnPropertyChanged("pName");
            }
        }

        public int pAge
        {
            get
            {
                return age;
            }
            set
            {
                if(!Regex.IsMatch(value.ToString(),"[0-9]"))
                {
                    throw new ArgumentException("Age field must be in number.");
                }

                if(value < 18 || value > 100)
                {
                    throw new ArgumentException("Age field must be 18-100.");
                }

                age = value;
                OnPropertyChanged("pAge");
            }
        }


        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged(string data)
        {
            if (PropertyChanged != null)
            { 
                PropertyChanged(this,new PropertyChangedEventArgs(data));
            }
        }

    }