0

我正在开发 WPF 应用程序。在我的应用程序中,有不同的表格可以保存数据。我想在按钮单击或失去控制焦点时验证数据。我希望 WPF 验证像 ASP.Net 验证一样工作。

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

我在google上做了很多研发。但我确实通过设置解决方案找到了任何正确的设置。

请帮帮我。

4

1 回答 1

-1

In this example I show you two text box with validation...

XAML Coding......

    <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# Coding

    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));
            }
        }

    }
于 2013-04-17T19:30:33.313 回答