首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

WPF,数据印证

2013-08-13 
WPF,数据验证class Person{private int agepublic int Age{get { return age }set{if (value 42)throw

WPF,数据验证


class Person
    {
        private int age;
        public int Age
        {
            get { return age; }
            set
            {
                if (value < 42)
                    throw new Exception("年龄太小");
                else
                    age = value;
            }
        }
    }


<Grid HorizontalAlignment="Left" Height="372" VerticalAlignment="Top" Width="467">
    <Grid.Resources>
        <local:Person x:Key="person1"></local:Person>
    </Grid.Resources>
    <TextBox HorizontalAlignment="Left" Height="23" Margin="87,173,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120">
        <TextBox.Text>
            <Binding Source="{StaticResource person1}" Path="Age" ValidatesOnExceptions ="True"/>
        </TextBox.Text>
    </TextBox>    
</Grid>



关于ExceptionValidationRule验证,ExceptionValidationRule类是一个内置的规则,也就是没有什么特殊的规则,它只是检查在绑定源属性更新过程中引发的异常。


问题:
当在文本框中输入20,移开鼠标之后,会产生异常,难道这就验证吗?我试过,就算是把ValidatesOnExceptions 设为false,仍然会产生异常。那ExceptionValidationRule岂不是没有产生作用吗?
------解决方案--------------------


那就比较奇怪了,确定你的程序里没有别的代码?
你用下面的代码测试一下呢:


<Window x:Class="WpfApp1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApp1"
    Title="" Height="400" Width="550" >
    <StackPanel>
        <StackPanel.Resources>
            <local:Person x:Key="person1"></local:Person>
        </StackPanel.Resources>
        <TextBox>
            <TextBox.Text>
                <Binding Source="{StaticResource person1}" Path="Age" ValidatesOnExceptions ="True"/>
            </TextBox.Text>
        </TextBox>
        <TextBox></TextBox>
    </StackPanel>
</Window>

using System;
using System.Windows;

namespace WpfApp1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}

class Person
{
private int age;
public int Age
{
get { return age; }
set
{
if (value < 42)
throw new Exception("年龄太小");
else
age = value;
}
}
}
}

热点排行