【发布时间】:2009-06-25 18:03:08
【问题描述】:
我们都知道开箱即用的 WPF 验证有多糟糕。我正在尝试一件非常简单的事情,但由于某种原因它总是失败。我有一个 TextBox,我唯一的要求是验证用户在 TextBox 中输入的内容。 TextBox 绑定到具有 FirstName 和 LastName 属性的 Customer 对象。
这是 XAML 代码:
<TextBox Style="{StaticResource TextBoxStyle}" Grid.Column="1" Grid.Row="0" Height="20" Width="100" Margin="10">
<TextBox.Text>
<Binding Path="FirstName" >
<Binding.ValidationRules>
<ExceptionValidationRule />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
这是 Customer 类的 FirstName 属性:
public string FirstName
{
get { return _firstName;}
set
{
if(String.IsNullOrEmpty(value))
throw new ApplicationException("FirstName cannot be null or empty!");
_firstName = value;
OnPropertyChanged("FirstName");
}
}
即使我在 FirstName(值)为 null 或为空时引发异常,但只有在我在 TextBox 中键入内容然后删除它然后关闭选项卡时才会处理它。原因是它依赖于属性更改事件。但即使我将 TextBox 绑定放在 Focus 上,它也不会触发验证。
更新:
处理此问题的最丑陋的方法之一是将 String.Empty 分配给 Window.Loaded 事件上的 TextBoxes:
void AddCustomerWindow_Loaded(object sender, RoutedEventArgs e)
{
// get all the textboxes and set the property to empty strings!
txtFirstName.Text = String.Empty;
txtLastName.Text = String.Empty;
}
下面是绑定代码:
public AddCustomerWindow()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(AddCustomerWindow_Loaded);
gvAddCustomer.DataContext = new Customer();
}
【问题讨论】:
标签: wpf validation textbox