【问题标题】:WPF - How can I validate a new instance of an object?WPF - 如何验证对象的新实例?
【发布时间】:2013-12-09 19:57:01
【问题描述】:

我有这门课

public class Doctor
{
    private string licenseNumber;
    public string LicenseNumber
    {
        get
        {
            return this.licenseNumber;
        }
        set
        {
            if (value.Length > 4)
                throw new MyException("License Number can't be more then 4 digits.\n");
            if (!new Regex("^[0-9]*$").Match(value).Success) // Allow only numbers
                throw new MyException("Only numbers are allowed in a License Number.\n");
            this.licenseNumber = value.PadLeft(4,'0'); // Pad with zeros to 4 digits
        }
    }
    private string name;
    public string Name
    {
        get
        {
            return this.name;
        }
        set
        {
            if (!new Regex("^[a-zA-Z ]*$").Match(value).Success) // Allow only letters and spaces 
                throw new MyException("Only letters and spaces are allowed in a name.\n");
            this.name = value;
        }
    }
    private string phoneNumber;
    public string PhoneNumber
    {
        get
        {
            return this.phoneNumber;
        }
        set
        {
            {
                if (!new Regex("^0[2-9]-[0-9]{7}$").Match(value).Success) // allow only numbers in format 0[2-9]-xxxxxxx
                    throw new MyException("ERROR: only numbers in format 0[2-9]-xxxxxxx are legal\n");
                this.phoneNumber = value;
            }
        }
    }

}

以及其中的更多属性。 当然,这个类的 ctor 只接受内部有值的 ctor 形式,并将值输入到 props 中。 现在,我创建了一个表单,用户可以在其中添加一个新的医生。 事情是 - 我想在用户点击“添加”之前验证表单。 这是我在 XML 中的“添加”表单的简短版本:

<Window x:Class="PLForms.AddDoctor"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="AddDoctor" Height="431" Width="381" mc:Ignorable="d" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:my="clr-namespace:BE;assembly=BE" Loaded="Window_Loaded" Background="White" ResizeMode="CanResizeWithGrip" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" Margin="12" HorizontalAlignment="Left" VerticalAlignment="Top">
<Window.Resources>
    <CollectionViewSource x:Key="doctorViewSource" d:DesignSource="{d:DesignInstance my:Doctor, CreateList=True}" />
</Window.Resources>
    <Grid Height="367" Name="grid1" Width="296" Margin="12" HorizontalAlignment="Center" VerticalAlignment="Center">
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="29" />
        </Grid.RowDefinitions>
        <Grid DataContext="{StaticResource doctorViewSource}" HorizontalAlignment="Left" Margin="19,13,0,0" Name="grid2" VerticalAlignment="Top">
            <Label Content="Name:" Grid.Column="0" Grid.Row="0" HorizontalAlignment="Left" Margin="3" VerticalAlignment="Center" />
            <TextBox Grid.Column="1" Grid.Row="0" Height="23" HorizontalAlignment="Left" Margin="3" Name="nameTextBox" Text="{Binding Path=Name, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}" VerticalAlignment="Center" Width="120" />
            <Label Content="Phone Number:" Grid.Column="0" Grid.Row="3" HorizontalAlignment="Left" Margin="3" VerticalAlignment="Center" />
            <TextBox Grid.Column="1" Grid.Row="3" Height="23" HorizontalAlignment="Left" Margin="3" Name="phoneNumberTextBox" Text="{Binding Path=PhoneNumber, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}" VerticalAlignment="Center" Width="120" />
        </Grid>
        <Button Content="Add" Name="Add" BorderBrush="#FF612355" Foreground="White" Click="Add_Click" Margin="0,326,0,0" Grid.RowSpan="2">
            <Button.Background>
                <LinearGradientBrush EndPoint="1,0.5" StartPoint="0,0.5">
                    <GradientStop Color="Black" Offset="0" />
                    <GradientStop Color="#85081DDA" Offset="0.893" />
                </LinearGradientBrush>
            </Button.Background>
        </Button>
    </Grid>

现在,我认为只有在我以某种方式设置“DataContext”时才会激活数据验证。我尝试在表单中设置一个示例 Doctor 对象,将 DataContext 分配给该对象的实例,然后 - 当用户将数据更新为非法数据时 - 它激活验证,并且在文本框周围标记了红色边框。 但我正在寻找如何“激活”验证,即使 之前没有 Doctor 实例 - 当用户得到一个空白表格时,自己填写,然后才尝试点击“添加” . 我的问题是,通过这种方式,我不能将 DataContext 属性附加到任何东西,因为我没有 Doctor 实例,当然我不能创建一个空的实例,因为所有异常都是我自己创建的。 . 我很高兴知道添加数据到数据库的逻辑是什么,并在之前验证它,而不仅仅是更新。 T

【问题讨论】:

    标签: wpf validation instance datacontext


    【解决方案1】:

    你看过validation attributes吗?这应该使您的代码更清晰,并且您不必再抛出异常,因为用户将无法将无效数据添加到数据库中。

    【讨论】:

    • 基本上你是对的,它真的是更干净的方式。但例外是有原因的。这个类还有一些其他的植入,不是所有的都通过 UI。因此,例外是“基本”验证器,它确保无效数据将进入类。问题是我是否可以在表单中使用它。
    • 我相信如果你要在绑定到 UI 时在 setter 上抛出异常,这有点过头了?是否有任何类/对象可以设置那些不是来自 UI 的属性?
    猜你喜欢
    • 2021-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-07
    • 2023-03-07
    • 2013-11-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多